Custom form ajax callback not firing

Created on 26 January 2023, over 2 years ago
Updated 26 February 2023, over 2 years ago

Hi, I have a very simple custom form to send an email with some information. I want to show this form within a node, in a twig.

In theme_preprocess_node I create the variable with the form:
$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\my_ajax_form');
$variables['my_ajax_form'] = $form;

When I test the form in the page I created in my_module.routing everything works ok but when I submit the form from the node, ajax callback is not called and the submit sends me to a page not found.

  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

        $form['intro'] = array(
            '#type'     => 'markup',
            '#markup'   => t('Si nos dejas tu mail te enviaremos la información de la sede a tu correo'),
            '#title'    => NULL,
        );
        $form['email'] = array(
            '#type'         => 'email',
            '#placeholder'  => t('Escribe aquí tu e-mail'),
            '#title'        => NULL,
            '#required'     => TRUE,
            '#prefix'       => '<div id="user-email-result"></div>'
        );        
        $form['message'] = [
          '#type' => 'markup',
          '#markup' => '<div class="result_message"></div>'
        ];
        $form['actions'] = [
          '#type' => 'button',
          '#value' => $this->t('Submit'),
          '#ajax' => [
            'callback' => '::setMessage',
            'type' => 'throbber',
          ],
        ];
  }
  public function setMessage(array $form, FormStateInterface $form_state) {

    $response = new AjaxResponse();
    $response->addCommand(
      new HtmlCommand(
        '.result_message',
        '<div class="my_top_message">'.$mensaje.'</div>'),
    );
    return $response;

   }
   
    /**
      * {@inheritdoc}
    */
    public function validateForm(array &$form, FormStateInterface $form_state) {
      
    }
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
   
    }

It's driving me crazy. Any help?

💬 Support request
Status

Closed: works as designed

Version

9.5

Component
Ajax 

Last updated 3 days ago

Created by

🇪🇸Spain jeepster

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024