1

I'm trying to add contact form with AJAX callback, called from another form. Form is embedding as well, but when I submit it only page is reloading and form doesn't send any data (in my case it's a contact form, and I can't see any created contact message in backoffice after submitting).

function somemodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['somefield']['widget']['#ajax'] = [
    'callback' => 'somemodule_form_conditional_ajax',
    'method' => 'html',
    'wrapper' => 'form-conditional-ajax-wrapper',
    'event' => 'change',
  ];
  $form['#suffix'] = '<div id="form-conditional-ajax-wrapper"></div>'  

}


function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $output = \Drupal::service('entity.form_builder')->getForm($contact_message);
  }

  return $output;
}
0

1 Answer 1

1

I just had this issue myself. Try this:

use Drupal\Component\Serialization\Json;
use Drupal\Core\Render\BubbleableMetadata;

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $form = \Drupal::service('entity.form_builder')->getForm($contact_message);
    $output = render($form);

    $data = BubbleableMetadata::createFromRenderArray($form);
    $attachments = $data->getAttachments();
    $settings = '';
    if(!empty($attachments['drupalSettings'])) {
      $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
      $settings .= Json::encode($attachments['drupalSettings']);
      $settings .= ');</script>';
    }

    $output .= $settings;
  }

  return $output;
}

The only thing I'm unsure about is if the $output requires an array - what I've given you is a string. So it may not work.

Your Answer

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

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