Hi, I am trying to add a parameter onto a node add form but not having any luck. Example, I'd like to have something like this: node/add/application/333 where 333 is another ID that I can use to control some things on the add form. Can someone steer me in the right direction?

Comments

slewazimuth’s picture

The documentation on passing parameters in routes covers what you desire in detail.

dmudie’s picture

Thanks. I've looked that over and know how to use parameters in routes for my custom pages. However, I'm getting stuck on how to define the controller. I'd like to use the core node add code and just add my wildcard to it so I can use it in form_alter hook. For example, for a path like '/node/add/application/{job_id}'

Thanks and I appreciate your reply!

jaypan’s picture

In this case, I would probably do two things:

1) Create a new route for the form

2) Extend NodeForm to expect the new parameter.

example.routing.yml:

example.node_form:
  path: '/node/add/application/{some_value}'
  defaults:
    _controller: '\Drupal\example\Controller\PageController::exampleNodeFormPage'
  ...

Then you build your controller:

<?php

namespace Drupal\example\Controller;

class PageController {

  /**
   * Add form.
   */
  public function exampleNodeFormPage($someId) {
    return [
      'form' => \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleNodeForm', $someId);
    ];
  }
}

Then in your form, you can do the following:

<?php

namespace Drupal\example\Form;

use Drupal\node\NodeForm; 

class ExampleNodeForm extends NodeForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state, $someId = NULL) {
    // Added as a fallback in case a developer uses this form without passing
    // $someId:
    if (is_null($someId)) {
      $form = [
        '#prefix' => '<p class="error">',
        '#suffix' => '</p>',
        '#markup' => $this->t('Form is missing $someId which is required'),
      ];
    }
    else {
      $form = parent::form($form, $form_state);
      // Do something with $form and $some_id
    }

    return $form;
  }
}

Note that the interface means you must set the default for $someId to NULL, or you will get an error. That is why the sanity check on $someId is included in the form definition.

Also note that if the ID refers to a node, or some other entity, it would be better to upcast it into that entity before passing to the form definition.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
dmudie’s picture

Thank you Jaypan - this is great. I really appreciate your time and explanation. Extending the node form is the piece I was missing. 

dmudie’s picture

Getting an error trying to load the form

Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() 

I would have expected the base form ID would be 'node_form" but do I need to set that somehow?

jaypan’s picture

I think I know what is going on here, but when are you getting this error, on form load, or submit?


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
dmudie’s picture

It's happening on load.

jaypan’s picture

NodeForm extends EntityForm, which has a method, setEntity(). You need to set the entity on the form. You'll have to track down how they do this in code - do they load the form, then call this method, before rendering the form? I'm not sure, but looking at that error, this would appear to be your issue.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
ilechcod’s picture

I'm still getting the getEntityTypeId() on null error. Have tried setting it in my form class like this

$this->entity = $form_state->getFormObject()->getEntity()

But it doesn't work. Pls how did you guys solve this error? 

DavilaG’s picture

I'm trying to pass some parameters to my node/add/CONTENTTYPE form and implemented this script, but I'm getting the same  getEntityTypeId() error. Did you manage to solve it? If so, can you please share the complete script?

ckl’s picture

I am also getting this error

preethy211’s picture

Am trying to add an argument to the path node/add/legals/113, where legals-> machine name of my content type and 113 is the node id. I tried your code but am getting this error,

ReflectionException: Class \Drupal\legals\Controller\PageController does not exist in ReflectionMethod->__construct() (line 136 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

Drupal\Core\Entity\EntityResolverManager->setParametersFromReflection(Array, Object) (Line: 221)
Drupal\Core\Entity\EntityResolverManager->setRouteOptions(Object) (Line: 48)
Drupal\Core\EventSubscriber\EntityRouteAlterSubscriber->onRoutingRouteAlterSetType(Object, 'routing.route_alter', Object)
call_user_func(Array, Object, 'routing.route_alter', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('routing.route_alter', Object) (Line: 189)
Drupal\Core\Routing\RouteBuilder->rebuild() (Line: 83)
Drupal\Core\ProxyClass\Routing\RouteBuilder->rebuild() (Line: 1087)
drupal_flush_all_caches() (Line: 192)
Drupal\system\Form\PerformanceForm->submitCacheClear(Array, Object)
call_user_func_array(Array, Array) (Line: 114)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 52)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 591)
Drupal\Core\Form\FormBuilder->processForm('system_performance_settings', Array, Object) (Line: 320)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 91)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 694)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

My Project Code Structure looks like,

legals (path-sites/all/modules/custom/legals)

1. legals.info.yml

2. legals.routing.yml

3. src

     3.1 Controller

            3.1.1 LegalsController.php

     3.2 Form

           3.2.1 Legals.php

I have attached the code for each file
 

1. legals.info.yml:

name: Legals
description: Custom module to create a new route for the form.
package: Custom Modules

type: module
core: 8.x

2. legals.routing.yml:

legals.node_form:
  path: '/node/add/legals/{node_id}'
  defaults:
    _controller: '\Drupal\legals\Controller\PageController::legalsNodeFormPage'
    _title: 'Legals'
  requirements:
    _permission: 'access content'

3.1.1 LegalsController.php:

<?php

namespace Drupal\legals\Controller;

    class PageController {
        /**
         * Add form.
         */
        public function legalsNodeFormPage($nodeId) {
          return [
            'form' => \Drupal::formBuilder()->getForm('\Drupal\legals\Form\LegalsNodeForm', $nodeId);
          ];
        }
    }

3.2.1 Legals.php:

<?php

namespace Drupal\legals\Form;

use Drupal\node\NodeForm;

class LegalsNodeForm extends NodeForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state, $nodeId = NULL) {
    // Added as a fallback in case a developer uses this form without passing
    // $nodeId:
    if (is_null($nodeId)) {
      $form = [
        '#prefix' => '<p class="error">',
        '#suffix' => '</p>',
        '#markup' => $this->t('Form is missing $nodeId which is required'),
      ];
    }
    else {
      $form = parent::form($form, $form_state);
      // Do something with $form and $nodeId
        dpm($nodeId);
        dpm($form);
    }

    return $form;
  }
}

Can you please help me with this error?

Thanks Much!

shablm’s picture

Hi Jaypan,

Am trying to add an argument to the path node/add/legals/113, where legals-> machine name of my content type and 113 is the node id. I tried your code but am getting this error,

ReflectionException: Class \Drupal\legals\Controller\PageController does not exist in ReflectionMethod->__construct() (line 136 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

My Project Code Structure looks like,

legals (path-sites/all/modules/custom/legals)

1. legals.info.yml

2. legals.routing.yml

3. src

     3.1 Controller

            3.1.1 LegalsController.php

     3.2 Form

           3.2.1 Legals.php

I have attached the code for each file
 

1. legals.info.yml:

name: Legals
description: Custom module to create a new route for the form.
package: Custom Modules
 
type: module
core: 8.x

2. legals.routing.yml:

legals.node_form:

path: '/node/add/legals/{node_id}'
  defaults:
    _controller: '\Drupal\legals\Controller\PageController::legalsNodeFormPage'
    _title: 'Legals'
  requirements:
    _permission: 'access content'

3.1.1 LegalsController.php:

<?php
 
namespace Drupal\legals\Controller;
 
    class PageController {
        /**
         * Add form.
         */
        public function legalsNodeFormPage($nodeId) {
          return [
            'form' => \Drupal::formBuilder()->getForm('\Drupal\legals\Form\LegalsNodeForm', $nodeId);
          ];
        }
    }

3.2.1 Legals.php:

<?php
 
namespace Drupal\legals\Form;
 
use Drupal\node\NodeForm;
 
class LegalsNodeForm extends NodeForm {
 
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state, $nodeId = NULL) {
    // Added as a fallback in case a developer uses this form without passing
    // $nodeId:
    if (is_null($nodeId)) {
      $form = [
        '#prefix' => '<p class="error">',
        '#suffix' => '</p>',
        '#markup' => $this->t('Form is missing $nodeId which is required'),
      ];
    }
    else {
      $form = parent::form($form, $form_state);
      // Do something with $form and $nodeId
        dpm($nodeId);
        dpm($form);
    }
 
    return $form;
  }
}

Can you please help me with this error?

Also, regarding your comment on upcasting node ID, how do I do that?

Thanks Much!

Preethi

jaypan’s picture

You've named your file LegalsController, but then you named the class PageController. You'll have to change the class name to LegalController.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
preethy211’s picture

Can you please tell me what must be the first line of the legals.routing.yml file?

You have mentioned it to be example.node_form:

I tried giving it as legals.legalsNodeFormPage: in my legals.routing.yml file, but it says non existent service. Can you please correct me on this?

Thanks Much!

Preethi

jaypan’s picture

The name of the class must be the same as the name of the file.

In your routing file, you've said to look for the class PageController. You named the file LegalsController.php, and then you made the class name PageController. These all need to be the same, so the easiest thing to do is change the name of your file from LegalsController.php to PageController.php.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
preethy211’s picture

yeah, i got your point. Thank you so much, that error is gone.

But my class throws a run time exception saying the argument is nullable although am passing an argument to it. This is because on the view where am passing the argument it throws this error,

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "content_moderation.moderation_information". in Drupal\Component\DependencyInjection\Container->get() (line 153 of core/lib/Drupal/Component/DependencyInjection/Container.php).

I guess there is some error with my legals.routing.yml file.

You have mentioned in your comment like this,

example.node_form:
  path: '/node/add/application/{some_value}'
  defaults:
    _controller: '\Drupal\example\Controller\PageController::exampleNodeFormPage'
  ...

My file is like this,

legals.legalsNodeFormPage:   /*is *this *line *right???*/
  path: '/node/add/legals/{nid}'
  defaults:
    _controller: '\Drupal\legals\Controller\LegalsController::legalsNodeFormPage'
    _title: 'Legals'
  requirements:
    _permission: 'access content'

Is my first line on this file is right? I want to know what is causing this error.

Thanks Much in advance!

Preethi