bambamboole bambamboole - 6 months ago 156
Ajax Question

Drupal 8 Mailchimp Ajax Signup Block

I try to ajaxify the Drupal 8 Mailchimp SignUp Block but I stuck with the AjaxResponse.

This is my Form alter hook:

function mailchimp_ajax_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {

if ($form_id != 'mailchimp_signup_subscribe_block_form') {
return;
}
$form['submit']['#ajax'] = [
'callback' => 'mailchimp_ajax_form_callback',
'prevent' => 'click',
'progress' => array(
'type' => 'throbber',
'message' => t('Submitting data...')
)
];

}


This is my callback function:

function mailchimp_ajax_form_callback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {


$response = new \Drupal\Core\Ajax\AjaxResponse();

$response->setContent('Response');
return $response;
}


But in Chrome console there is only an error:

Uncaught AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /node?ajax_form=1
StatusText: OK
ResponseText: Response


The Signup works, but my question is how can I get the mailchimp response and put it in a valid AjaxResponse?

Answer

My "working" solution now is:

alter the form block, add an ajax callback function, prevent click and adds some ajax progress visualization.

/**
 * Implements hook_form_FORM_ID_alter()
 *
 * @param \Drupal\mailchimp_signup\Form\MailchimpSignupPageForm $form
 * @param \Drupal\Core\Form\FormStateInterface                  $form_state
 * @param                                                       $form_id
 */
function mailchimp_ajax_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {

  if ($form_id != 'mailchimp_signup_subscribe_block_form') {
    return;
  }
  $form['submit']['#ajax'] = [
    'callback' => 'mailchimp_ajax_form_callback',
    'prevent'  => 'click',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Submitting data...')
    )
  ];

}

This is the Ajax Callback:

I create a new AjaxResponse Object and an array of the Drupal messages via drupal_get_messages(). Then some kind of hack to get the right message.

and add an ReplaceCommandObject which replaces the form with the Mailchimp message.

function mailchimp_ajax_form_callback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {


  $response = new \Drupal\Core\Ajax\AjaxResponse();

  $messages = drupal_get_messages();

  $message = $messages['status'][0];

  if(!$message){
    $message = $messages['warning'][0];
  }

  $response->addCommand(new \Drupal\Core\Ajax\ReplaceCommand('#mailchimp-signup-subscribe-block-form', $message));

  return $response;
}

I think there are much more elegant ways to get this. I still don't know why the submitForm Method of The Mailchimp Form is still invoked...

Comments