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

Indeed, one way to do this is to implement CommandInterface in a new class, as described here: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8 . This method adds the new command to Druapl.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 in the example here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x

My minimalistic 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();
};
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.