I have a form defined in mymodule/src/Form/myForm.php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class myForm extends FormBase {
/**
* Specify the form ID.
*/
public function getFormId() {
return 'mymodule_myform';
}
/**
* Build the actual form.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Form API code here...
Originally, this routing worked fine and the form displayed at the correct path:
mymodule.single_tab:
path: '/node/{node}/edit/performance'
defaults:
_form: '\Drupal\mymodule\Form\myForm'
_title: 'Add performance'
Then I needed to add a custom access check, restricting to a specific content type:
mymodule.single_tab:
path: '/node/{node}/edit/performance'
defaults:
_title: 'Add performance'
_controller: '\Drupal\mymodule\Controller\mymoduleController::content'
requirements:
_custom_access: '\Drupal\mymodule\Controller\mymoduleController::checkAccess'
The access check works fine. Now I think I have to display my form in the controller:
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\Entity\Node;
/**
* Controller for Add Performance single tab.
*/
class mymoduleController extends ControllerBase {
/**
* Returns the add single performance form.
*/
public function content() {
$form = $this->formBuilder->getForm('Drupal\mymodule\Form\myForm');
return [
'#type' => 'markup',
'#markup' => $form
];
}
This fails to display the form, and I get:
Call to a member function getForm() on null
I tried defining my form builder class inside the controller instead, but same result. What am I doing wrong?
return $form;
2) the error message is because you didn't inject the form builder service or didn't use the static\Drupal::formBuilder()
3)_form
invokes a controller too, a special form controller.