1

This is my code in routing.yml file

test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'

I need to get the value of node in the form controller buildForm function.

How can I access that? Any help?

1
  • $node = \Drupal::request()->get('node'); I think, it would work for your situation :)
    – Leopathu
    Jul 19, 2016 at 11:02

2 Answers 2

3

Update the .routing.yml file like so:

test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'
    node: \d+
  options:
    _node_operation_route: TRUE

Then use it in your form controller the following way:

namespace Drupal\test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class Test extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $form['placeholder'] = [
      '#markup' => t('This is the form for @node_title.', [
        '@node_title' => $node->getTitle(),
      ]),
    ];

    return $form;
  }
}
3
  • I am sorry.This resulted an error 'Object of class Drupal\node\Entity\Node could not be converted to string' Jul 19, 2016 at 11:27
  • Did you clear the cache after updating the routing.yml file? Jul 19, 2016 at 11:29
  • You're welcome. Don't forget to mark it as a solution so others with the same problem know that this answered the question. Comments can get deleted after some time. Jul 20, 2016 at 5:59
0

There are one way with two approaches:

Either calling the request service statically:

  • $request_param= \Drupal::request()->query->get('myparam');

Or call it via Dependency injection:

return new static(
  $container->get('request_stack')
);

And then just add to the end of the constructor's argument list: RequestStack $request_stack

And save it as own property, which you can use later: $this->requestStack = $request_stack;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.