View source
<?php
namespace Drupal\ajax_test\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\MessageCommand;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
class AjaxTestMessageCommandForm implements FormInterface {
public function getFormId() {
return 'ajax_test_message_command_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['alternate-message-container'] = [
'#type' => 'container',
'#id' => 'alternate-message-container',
];
$form['button_default'] = [
'#type' => 'submit',
'#name' => 'makedefaultmessage',
'#value' => 'Make Message In Default Location',
'#ajax' => [
'callback' => '::makeMessageDefault',
],
];
$form['button_alternate'] = [
'#type' => 'submit',
'#name' => 'makealternatemessage',
'#value' => 'Make Message In Alternate Location',
'#ajax' => [
'callback' => '::makeMessageAlternate',
],
];
$form['button_warning'] = [
'#type' => 'submit',
'#name' => 'makewarningmessage',
'#value' => 'Make Warning Message',
'#ajax' => [
'callback' => '::makeMessageWarning',
],
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
public function makeMessageDefault() {
$response = new AjaxResponse();
return $response
->addCommand(new MessageCommand('I am a message in the default location.'));
}
public function makeMessageAlternate() {
$response = new AjaxResponse();
return $response
->addCommand(new MessageCommand('I am a message in an alternate location.', '#alternate-message-container', [], FALSE));
}
public function makeMessageWarning() {
$response = new AjaxResponse();
return $response
->addCommand(new MessageCommand('I am a warning message in the default location.', NULL, [
'type' => 'warning',
'announce' => '',
]));
}
}