I found different type of ajax commands like htmlCommand, invoke command etc. I want to create a custom ajax command that sets the response of ajax callback as the value of specifying markup in the callback argument. Is it possible? I created one as per this tutorial.
public function ajax_call_back_function() {
$response = new AjaxResponse();
$element = $form_state->getTriggeringElement();
$returnDelta = $element['#array_parents'][2]; // get levels
$delta = $element['#value']; // eg : 944 THis is the ata i want to set as the value of markup
$response->addCommand(new ReadMessageCommand($delta, $returnDelta));
return $response;
}
The ReadMessageCommand
class is the following.
class ReadMessageCommand implements CommandInterface {
protected $message;
// Constructs a ReadMessageCommand object.
public function __construct($message,$level) {
$this->message = $message;
$this->level = $level;
}
// Implements Drupal\Core\Ajax\CommandInterface:render().
public function render() {
return array(
'command' => 'readMessage',
'message' => $this->message,
'level' => $this->level,
);
}
}
I include a JavaScript file.
(function($, Drupal) {
Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
$('#edit-field-region-management-'+response.level+'-valueregion').val(response.message);
};
})(jQuery, Drupal);
The controller class is the following.
class AjaxCommandsAddController extends ControllerBase {
public function messagesPage() {
$page[] = array(
'#type' => 'markup',
'#markup' => $content,
);
// Attach JavaScript library.
$page['#attached']['library'][] = wms_ajax_commands/wms_ajax_commands.commands';
return $page;
}
}
But when executing, I get the following error.
Fatal error: Class 'Drupal\Core\Ajax\ReadMessageCommand' not found in Path-to-module/src/Plugin/Field/FieldWidget/RegionWidgetType.php