3

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

1
  • Use a wrapper element. Where are you calling your ajax_callback_function()? Commented Mar 28, 2016 at 2:47

1 Answer 1

4

It seems like you have a namespace error(s). The error happens in a file you didn't mention RegionWidgetType.php. It's trying to use Drupal\Core\Ajax\ReadMessageCommand which as I understand it is something you made. Which means that the namespace should definitely not be \DrupalCore\... for the auto load to work.

The name space of your custom files should be Drupal\MODULE_NAME\folder\structure

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.