I'm submitting a form via AJAX.
$response = new AjaxResponse();
It's not using the Drupal default dialog, so I can't use $response->addCommand(new CloseModalDialogCommand()); after all validation is done. It's using jQuery Modal.
Validation is working fine. After all things done I want to execute Javascript in submitForm function.
Which function should I use? I need to check for example alert(1).
I have to close window using Javascript & Alert message as well. I tried AlertCommand but not working.
Following this example: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x But not working
I have below code
modules/demo_test/src/Form/DemoTestForm.php
namespace Drupal\demo_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
class DemoTestForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#prefix'] = '<div id="demo-test--modal-form">';
$form['#suffix'] = '</div>';
$form['firstname'] = [
'#type' => 'textfield',
'#title' => $this->t('First name'),
'#required' => TRUE,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#name' =>'submit',
'#type' => 'submit',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::ajaxSubmitForm',
'event' => 'click',
],
];
$form['#attached']['library'][] = 'demo_test/demo';
return $form;
}
public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) {
drupal_get_messages();
$response = new AjaxResponse();
if ($form_state->getErrors()) {
unset($form['#prefix']);
unset($form['#suffix']);
$form['status_messages'] = [
'#type' => 'status_messages',
'#weight' => -10,
];
$response->addCommand(new HtmlCommand('#demo-test-modal-form', $form));
}
return $response;
}
public function getFormId() {
return 'demo_test_form';
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new InvokeCommand('html', 'trigger', array(
'triggerName',
array(
'foo' => 'bar',
),
)));
return $response;
}
}
modules/demo_test/js/demo.js
(function ($, Drupal) {
'use strict';
Drupal.behaviors.demo = {
attach: function (context, settings) {
$(document).on('triggerName', function(e, data) {
alert('data.foo'); // alerts string 'bar'
});
}
};
})(jQuery, Drupal);
jQuery(document).on('triggerName', function(e, data) {
alert(1);
alert('data.foo'); // alerts string 'bar'
});
It's not going in JS file & alert. JS file is loading fine.
InvokeCommanddefinitely works and is exactly how you would communicate from an AjaxResponse to trigger any arbitrary Javascript function or method.CloseModalDialogCommand. Two modules I wrote showing an example of this are iGrowl and SweetAlert. drupal.org/project/igrowl & drupal.org/project/sweetalert