Problem/Motivation
While attempting to render a custom form inside of a block, I discovered that using \Drupal::formBuilder()->getForm()
has varying results depending on "where" you call it from.
I originally was inserting it directly into my hook_theme() function in the .module file.
/**
* Implements hook_theme().
*/
function my_theme($existing, $type, $theme, $path) {
return [
'my_block' =>
[
'render element' => 'form',
'base hook' => 'form',
'variables' => [
'label' => NULL,
'description' => NULL,
'form' => \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm'),
],
],
];
}
While I make no argument that this was the "right" place to put this code, the form DID render. However, it did NOT submit or validate using the form's custom submission / validation hooks.
Once I moved the same basic code into the build() method of my Block's controller, it worked fine (I changed the hook_theme to have a NULL entry for the form variable instead of the \Drupal::formBuilder()->getForm()
method.
/**
* {@inheritdoc}
*/
public function build() {
return [
'#theme' => 'my_block',
'#description' => $this->configuration['description'],
'#form' => \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm'),
'#cache' => ['max-age' => 0],
];
}
A few additional details:
- When rendered through the block, the form's build method WAS being called (verified via debugger), although it required a cache clear to get it to trip the debugger
- When rendered through the block, the form's submit/validate methods were NOT being called (verified via debugger) even after a cache clear. Rather, the post from the form was being shoved into the browser's URL bar and the form was reloading empty.
- When rendered via a custom route (and not through the block rendering), the form worked fine (and tripped all expected submit/validation behaviors)
- The block was placed on a landing page via panelizer
Proposed resolution
Correct form rendering so that the submit / validation handlers fire properly, or update form rendering so that Drupal triggers an error and warns the user that they have implemented the method from a location that will not fully render the form.
Remaining tasks
TBD
User interface changes
TBD
API changes
TBD
Data model changes
TBD
Original report by mikemadison
TBD
Comments
Comment #2
mikemadison CreditAttribution: mikemadison at Acquia commentedComment #3
mikemadison CreditAttribution: mikemadison at Acquia commentedComment #4
mikemadison CreditAttribution: mikemadison at Acquia commentedComment #5
mikemadison CreditAttribution: mikemadison at Acquia commented