1

I have a method that is invoked by AJAX call, and it returns an AjaxResponse. It redirects the user with RedirectCommand, added to the response. However, I would like to change it to a conditional redirect. Is this possible with RedirectCommand, or any other way that uses the CommandInterface, preferably in a way that does not require implementing CommandInterface in a new class?

1 Answer 1

2

Indeed, one way to do this is to implement CommandInterface in a new class, as described in Creating AJAX Callback Commands in Drupal 8. This method adds the new command to Drupal.AjaxCommands.

However, if it's not desirable to implement the interface, a similar thing can be done with the existing InvokeCommand that implements CommandInterface, as seen in the example given in the InvokeCommand documentation page.

This is my minimalist example.

Server-side (NULL can be some CSS selector instead)

$response->addCommand(new InvokeCommand(NULL, 'customRedirect', ['/']));

Client-side

jQuery.fn.customRedirect = function(target) {
  if (something) {
    location.replace(target);
  }
  else {
    do_something_else();
  }
};

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.