I have a simple AJAX form that I can’t submit when the form is passed from module to the template in hook_preprocess_page. The same form works fine if sent from controller, it’s just that the layout is complicated and I prefer to write the HTML part in the twig file and integrate the form where it fits best.
The form class:
<?php namespace DrupalmymoduleForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class SubmissionForm extends FormBase { public function getFormId() { return 'mymodule_submission_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['#prefix'] = '<div id="submission-form-wrapper">'; $form['#suffix'] = '</div>'; $form['mail'] = array( '#title' => 'E-mail', '#type' => 'textfield', '#required' => TRUE, ); $form['actions'] = array( '#type' => 'actions' ); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => 'Submit', '#attributes' => array( 'class' => array( 'btn', 'btn-success', 'use-ajax-submit' ), ), '#ajax' => array( 'wrapper' => 'submission-form-wrapper', ) ); return $form; } public function validateForm(array &$form, FormStateInterface $form_state) { } public function submitForm(array &$form, FormStateInterface $form_state) { } }
The preprocess function:
/** * Implements hook_preprocess_HOOK(). */ function mymodule_preprocess_page(&$vars) { if (Drupal::service('path.matcher')->isFrontPage()) { $vars['page']['submission_form'] = Drupal::formBuilder()->getForm('DrupalmymoduleFormSubmissionForm'); } }
The error:
TypeError: Argument 1 passed to DrupalCoreAjaxAjaxResponse::setAttachments() must be of the type array, null given, called in /Volumes/Work/Git/myproject/public_html/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php on line 56 in DrupalCoreAjaxAjaxResponse->setAttachments() (line 37 of /Volumes/Work/Git/myproject/public_html/core/lib/Drupal/Core/Render/AttachmentsTrait.php).
- it’s a fresh Drupal 8.7.10
- devel and kint as contrib modules enabled
- core inline form errors enabled
- the form has only one required textfield and the submit button
Any suggestions on how to fix this?
Thank you!