Skip to content

Instantly share code, notes, and snippets.

@woprrr
Last active October 16, 2017 10:12
Show Gist options
  • Save woprrr/d771c9c858991ff0b90b71e2a94bcea9 to your computer and use it in GitHub Desktop.
Save woprrr/d771c9c858991ff0b90b71e2a94bcea9 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\ton_module\Ajax;
use Drupal\Core\Ajax\CommandInterface;
/**
* Provides an AJAX command ....
*
* This command is implemented in Drupal.AjaxCommands.prototype.ajaxRedirect.
*/
class AjaxRedirectCommand implements CommandInterface {
/**
* The url.
*
* @var string
*/
protected $url;
/**
* AjaxRedirectCommand constructor.
*
* @param $url
* @param $time
*/
public function __construct($url) {
$this->url = $url;
}
/**
* {@inheritdoc}
*/
public function render() {
return [
'command' => 'ajaxRedirect',
'url' => $this->url,
];
}
}
<?php
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$options = ['foo' => 'foo', 'bar' => 'bar'];
$form['dummy_radio'] = [
'#type' => 'radios',
'#title' => 'Dummy radios',
'#options' => $options,
'#attached' => [
'library' => [
'my_module/my_command.commands',
],
],
'#ajax' => [
'callback' => [$this, 'myDummyCallback'],
'event' => 'click',
'progress' => [
'type' => 'throbber',
'message' => 'Wait...',
],
],
'#required' => TRUE,
];
return $form;
}
public function myDummyCallback(array $form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$url = 'http://google.fr';
// TODO SOME STUFF ....
$response->addCommand(new AjaxRedirectCommand($url));
return $response;
}
/**
* @file
* Handles AJAX.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Ajax command for triggering redirect.
*
* @param {Drupal.Ajax} [ajax]
* An Ajax object.
* @param {object} [response]
* The Ajax response.
* @param {number} [status]
* The HTTP status code.
*/
Drupal.AjaxCommands.prototype.ajaxRedirect = function (ajax, response, status) {
window.location = response.url;
};
})(jQuery, Drupal, drupalSettings);
my_command.commands:
version: VERSION
js:
js/gistfile1.js: {}
dependencies:
- core/drupal.ajax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment