SlideShare a Scribd company logo
Demystifying AJAX Callback
Commands
(in Drupal 8)
2016.midcamp.org/node/48
MidCamp 2016
Background image modified version of "Chicago Bean" by Sergey Gabdurakhmanov
Mike Miles
@mikemiles86
Genuine ( )wearegenuine.com
mike­miles.com
Goals of this Session
Explain AJAX callback commands
Demonstrate AJAX callback commands
Outline custom AJAX callback commands
What are Callback Commands
Functions returned and invoked by all Ajax responses
Allow server to dictate client functionality
Defined by Drupal core (25) and Modules
Callback Commands: Server Side
Follows naming convention [CommandName]Command(.php)
Class that implements CommandInterface
Defines a 'render' method
Returns an associative array
Contains element with key of 'command'
'Command' value is name of JavaScript method
Anatomy of a Callback Command: PHP
01 use DrupalCoreAjaxCommandInterface;
02
03 // An AJAX command for calling [commandName]() JavaScript method.
04 class [CommandName]Command implements CommandInterface {
05
06 // Implements DrupalCoreAjaxCommandInterface:render().
07 public function render() {
08 return array(
09 'command' => '[commandName]', // Name of JavaScript Method.
10 // other request arguments...
11 );
12 }
13 }
[CommandName]Command.php
Callback command classes need to implement CommandInterface (lines #1 & #4). Must define a 'render'
method (lines #7 ­ #12), that returns an associative array. Associative array must contain an element
with the key of 'command' and a vlaue that is a name of the javascript method. Additional arguments are
passed as response data.
Callback Commands: Client Side
Wrapper for additional javascript
Method attached to 'Drupal.AjaxCommands.prototype' object
Takes 3 arguments
ajax
response
status
Anatomy of a Callback Command: JavaScript
01 /**
02 * [commandName description]
03 *
04 * @param {Drupal.Ajax} [ajax]
05 * @param {object} response
06 * @param {number} [status]
07 */
08 Drupal.AjaxCommands.prototype.[commandName] = function(ajax, response, status){
09
10 // Custom javascript goes here ...
11
12 }
Callback Command needs to be attached as a method to the Drupal.AjaxCommands.prototype object
(line #8). Command accepts three arguments and is a wrapper for additional javascript.
Callback Commands Are...
Functions returned and invoked by all Ajax responses
PHP Classes that implement CommandInterface
Methods attached to 'Drupal.AjaxCommands.prototype'
How to Use Callback Commands
Attach Drupal Ajax library to the requesting page
Create a callback method that returns an AjaxResponse object
Attach commands to AjaxResponse object using 'addCommand'
Example: The "Remove" Command
Example of using the remove callback command. Link triggers ajax request which returns response with
'remove' command targeting image id.
01 namespace Drupalremove_exampleController;
02 use DrupalCoreControllerControllerBase;
03
04 class RemoveExampleController extends ControllerBase {
05
06 // Return output for displaying an image and ajax link for removing it.
07 public static function demo() {
08 $output['description']['#markup'] = '<p>' . t('The following is an example of using
09 // ...
10 // Attach the ajax library.
11 $output['#attached']['library'][] = 'core/drupal.ajax';
12 // Return render array
13 return $output;
14 }
15 // ...
16 }
remove_example/src/Controller/RemoveExampleController.php
Pages that want to use Ajax need to include the ajax library. On line #11 attaching the core Drupal Ajax
library to the render array for the page.
01 namespace Drupalremove_exampleController;
02 use DrupalCoreControllerControllerBase;
03 use DrupalCoreAjaxAjaxResponse;
04 use DrupalCoreAjaxRemoveCommand;
05
06 class RemoveExampleController extends ControllerBase {
07 // ...
08 /**
09 * Callback method for removing image from 'remove-example' page.
10 *
11 * @return DrupalCoreAjaxAjaxResponse|mixed
12 */
13 public static function removeImage() {
14 // Create an Ajax Response object.
15 $response = new AjaxResponse();
16 // Add a remove command.
17 $response->addCommand(new RemoveCommand('#example_remove_wrapper'));
18 // Return the response object.
19 return $response;
20 }
21 }
remove_example/src/Controller/RemoveExampleController.php
Classes used for Ajax requests need to include needed classes (line #3, Line #4). Callback method needs
to return an ajax command (line #14) and attach commands using 'addCommand' method (line #16).
To Use Callback Commands...
Attach Drupal Ajax library to the requesting page
Create callback method that returns AjaxResponse
Attach commands to AjaxResponse object with 'addCommand'
Creating Custom Callback Commands
Requires a custom module
Need to define custom php classes
Need to define custom javascript methods
Custom Callback Commands: PHP
Follow naming convention [CommandName]Command(.php)
Implement CommandInterface
Define a 'render' method
Return an associative array with 'command' element
Place in 'src/Ajax/' directory of module
Example: SlideRemoveCommand
01 namespace Drupalremove_exampleAjax;
02
03 use DrupalCoreAjaxCommandInterface;
04 // An AJAX command for calling the jQuery slideUp() and remove() methods.
05 class SlideRemoveCommand implements CommandInterface {
06 // Constructs an SlideRemoveCommand object.
07 public function __construct($selector, $duration = NULL) {
08 $this->selector = $selector;
09 $this->duration = $duration;
10 }
11 // Implements DrupalCoreAjaxCommandInterface:render().
12 public function render() {
13 return array(
14 'command' => 'slideRemove',
15 'selector' => $this->selector,
16 'duration' => $this->duration,
17 );
18 }
19 }
remove_example/src/Ajax/SlideRemoveCommand.php
An example of creating a custom 'SlideRemove' callback command PHP Class. Class follows naming
conventions and implements CommandInterface (line #5). Defines a render method (line #12), which
returns an associative array with a 'command' keyed element. (lines #13 ­ #17).
Custom Callback Commands: JavaScript
Attach method to 'Drupal.AjaxCommands.prototype' object
Take 3 arguments
ajax
response
status
Add JavaScript to a custom library
Example: slideRemove
01 (function ($, window, Drupal, drupalSettings) {
02 'use strict';
03 // Command to slide up content before removing it from the page.
04 Drupal.AjaxCommands.prototype.slideRemove = function(ajax, response, status){
05 var duration = response.duration ? response.duration : "slow";
06
07 $(response.selector).each(function() {
08 $(this).slideUp(duration, function() {
09 $(this).remove();
10 });
11 });
12 }
13 })(jQuery, this, Drupal, drupalSettings);
remove_example/js/ajax.js
An example of creating a custom 'slideRemove' callback command javascript method. Attached to
'Drupal.AjaxCommands.prototype' object and accepts three arguments (line #4). Uses response data for
additional javascript functionality (lines #5 ­ #13).
Example: remove_example/remove-example library
01 remove-example:
02 version: VERSION
03 js:
04 js/ajax.js: {}
05 dependencies:
06 - core/drupal.ajax
remove_example.libraries.yml
Javascript file that contains custom 'slideRemove' command is added to a library deffinition (lines #3 ­
#4). Add core Drupal Ajax library as a dependency so that it is included (lines #5 ­ #6).
To Create Custom Callback Commands...
Use a custom module
Define classes that implements CommandInterface
Attach JavaScript method(s) to 'Drupal.AjaxCommands.prototype'
Using Custom Callback Commands
Attach custom library to the requesting page
Attach commands to AjaxResponse object with 'addCommand'
Example: The "slideRemove" Command
Example of using the custom slideRemove callback command. Link triggers ajax request which returns
response with 'slideRemove' command targeting image id.
01 namespace Drupalremove_exampleController;
02 use DrupalCoreControllerControllerBase;
03
04 class RemoveExampleController extends ControllerBase {
05
06 // Return output for displaying an image and ajax link for removing it.
07 public static function demo() {
08 $output['description']['#markup'] = '<p>' . t('The following is an example of using
09 // ...
10 // Attach custom Ajax command library.
11 $output['#attached']['library'][] = 'remove_example/remove-example';
12 // Return render array
13 return $output;
14 }
15 // ...
16 }
remove_example/src/Controller/RemoveExampleController.php
Custom Javascript library needs to be included on requesting page, so that methods are attached.
Attaching library to render array on line #11.
01 namespace Drupalremove_exampleController;
02 use DrupalCoreControllerControllerBase;
03 use DrupalCoreAjaxAjaxResponse;
04 use DrupalCoreremove_exampleSlideRemoveCommand;
05
06 class RemoveExampleController extends ControllerBase {
07 // ...
08 /**
09 * Callback method for removing image from 'remove-example' page.
10 *
11 * @return DrupalCoreAjaxAjaxResponse|mixed
12 */
13 public static function removeImage() {
14 // Create an Ajax Response object.
15 $response = new AjaxResponse();
16 // Add a remove command.
17 $response->addCommand(new SlideRemoveCommand('#example_remove_wrapper', 'slow'
18 // Return the response object.
19 return $response;
20 }
21 }
remove_example/src/Controller/RemoveExampleController.php
Like core callback commands, custom command classes have to be included in callback controller (line
#4) and added to AjaxResponse in callback method (line #17).
To Use Custom Callback Commands...
Attach custom library to the requesting page
Attach commands to AjaxResponse object with 'addCommand'
Review
AJAX Callback Commands Are...
Functions returned and invoked by all Ajax responses
PHP Classes implementing CommandInterface
Methods attached to 'Drupal.AjaxCommands.prototype' object
To Use AJAX Callback Commands...
Attach Drupal Ajax library to the requesting page
Create callback method that returns AjaxResponse
Attach commands to AjaxResponse object with 'addCommand'
To Create AJAX Callback Commands...
Use a custom module
Define classes that implements CommandInterface
Attach JavaScript methods to 'Drupal.AjaxCommands.prototype'
To Use Custom AJAX Callback Commands...
Attach custom library to the requesting page
Same process as using core commands
Resources
Drupal 8 AJAX Api: bit.ly/Drupal8Ajax
This Presentation: bit.ly/Mid16Ajax
Presentation Slides: bit.ly/Mid16AjaxSlides
Example Code: bit.ly/Mid16AjaxEx
Creating Commands in D8: bit.ly/D8AjaxCmds
 #midcamp  @WeAreGenuine D8 AJAX  /  Michael Miles
Thank You!
Feedback/Questions: @mikemiles86

More Related Content

What's hot

Sylius and Api Platform The story of integration
Sylius and Api Platform The story of integrationSylius and Api Platform The story of integration
Sylius and Api Platform The story of integration
Łukasz Chruściel
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Fabien Potencier
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
Michelangelo van Dam
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
Kiel Pykett
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
Aleix Vergés
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
Nuvole
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio pombi
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Daniel Bryant
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
Parashuram N
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016
John Napiorkowski
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
LEDC 2016
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 

What's hot (20)

Sylius and Api Platform The story of integration
Sylius and Api Platform The story of integrationSylius and Api Platform The story of integration
Sylius and Api Platform The story of integration
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 

Similar to MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
Singapore PHP User Group
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
AgileThought
 
Models, controllers and views
Models, controllers and viewsModels, controllers and views
Models, controllers and viewspriestc
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
Iegor Fadieiev
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
JoeDinaso
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207patter
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
Joshua Long
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
Lukas Smith
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2
Masao Maeda
 
Scala4sling
Scala4slingScala4sling
Scala4slingday
 
Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発
Recruit Lifestyle Co., Ltd.
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 

Similar to MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8 (20)

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Models, controllers and views
Models, controllers and viewsModels, controllers and views
Models, controllers and views
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
React lecture
React lectureReact lecture
React lecture
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2
 
Scala4sling
Scala4slingScala4sling
Scala4sling
 
Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発Springを用いた社内ライブラリ開発
Springを用いた社内ライブラリ開発
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 

More from Michael Miles

Inclusive Design: Thinking beyond accessibility
Inclusive Design: Thinking beyond accessibilityInclusive Design: Thinking beyond accessibility
Inclusive Design: Thinking beyond accessibility
Michael Miles
 
How to Foster Team Success
How to Foster Team SuccessHow to Foster Team Success
How to Foster Team Success
Michael Miles
 
How to Foster Team Success | Drupalcon 2017
How to Foster Team Success | Drupalcon 2017How to Foster Team Success | Drupalcon 2017
How to Foster Team Success | Drupalcon 2017
Michael Miles
 
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
Michael Miles
 
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
Michael Miles
 
The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017
Michael Miles
 
INCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond AccessibilityINCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond Accessibility
Michael Miles
 
Inclusive Design
Inclusive DesignInclusive Design
Inclusive Design
Michael Miles
 
The Flexibility of Drupal 8
The Flexibility of Drupal 8The Flexibility of Drupal 8
The Flexibility of Drupal 8
Michael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
Michael Miles
 
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right ModulesBadcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
Michael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
Michael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
Michael Miles
 
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modulesFlcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
Michael Miles
 
R.E.A.D: Four steps for selecting the right modules Midcamp 2015
R.E.A.D: Four steps for selecting the right modules Midcamp 2015R.E.A.D: Four steps for selecting the right modules Midcamp 2015
R.E.A.D: Four steps for selecting the right modules Midcamp 2015
Michael Miles
 
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
Michael Miles
 
To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...
Michael Miles
 

More from Michael Miles (17)

Inclusive Design: Thinking beyond accessibility
Inclusive Design: Thinking beyond accessibilityInclusive Design: Thinking beyond accessibility
Inclusive Design: Thinking beyond accessibility
 
How to Foster Team Success
How to Foster Team SuccessHow to Foster Team Success
How to Foster Team Success
 
How to Foster Team Success | Drupalcon 2017
How to Foster Team Success | Drupalcon 2017How to Foster Team Success | Drupalcon 2017
How to Foster Team Success | Drupalcon 2017
 
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
Inclusive Design: Thinking Beyond Accessibility | NERDSummit 2017
 
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
Inclusive Design: Thinking Beyond Accessibility | DCNL 2017
 
The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017
 
INCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond AccessibilityINCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond Accessibility
 
Inclusive Design
Inclusive DesignInclusive Design
Inclusive Design
 
The Flexibility of Drupal 8
The Flexibility of Drupal 8The Flexibility of Drupal 8
The Flexibility of Drupal 8
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
 
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right ModulesBadcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
Badcamp 2015 - R.E.A.D: Four Steps for Selecting The Right Modules
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of Drupal
 
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modulesFlcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
 
R.E.A.D: Four steps for selecting the right modules Midcamp 2015
R.E.A.D: Four steps for selecting the right modules Midcamp 2015R.E.A.D: Four steps for selecting the right modules Midcamp 2015
R.E.A.D: Four steps for selecting the right modules Midcamp 2015
 
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
How to R.E.A.D: Steps for how to select the correct module @NEWDCamp 2014
 
To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...To Patch or Custom: How to decide when to patch a contrib module or go custom...
To Patch or Custom: How to decide when to patch a contrib module or go custom...
 

Recently uploaded

Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 

Recently uploaded (20)

Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 

MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8

  • 1. Demystifying AJAX Callback Commands (in Drupal 8) 2016.midcamp.org/node/48 MidCamp 2016 Background image modified version of "Chicago Bean" by Sergey Gabdurakhmanov
  • 3. Goals of this Session Explain AJAX callback commands Demonstrate AJAX callback commands Outline custom AJAX callback commands
  • 4. What are Callback Commands Functions returned and invoked by all Ajax responses Allow server to dictate client functionality Defined by Drupal core (25) and Modules
  • 5. Callback Commands: Server Side Follows naming convention [CommandName]Command(.php) Class that implements CommandInterface Defines a 'render' method Returns an associative array Contains element with key of 'command' 'Command' value is name of JavaScript method
  • 6. Anatomy of a Callback Command: PHP 01 use DrupalCoreAjaxCommandInterface; 02 03 // An AJAX command for calling [commandName]() JavaScript method. 04 class [CommandName]Command implements CommandInterface { 05 06 // Implements DrupalCoreAjaxCommandInterface:render(). 07 public function render() { 08 return array( 09 'command' => '[commandName]', // Name of JavaScript Method. 10 // other request arguments... 11 ); 12 } 13 } [CommandName]Command.php Callback command classes need to implement CommandInterface (lines #1 & #4). Must define a 'render' method (lines #7 ­ #12), that returns an associative array. Associative array must contain an element with the key of 'command' and a vlaue that is a name of the javascript method. Additional arguments are passed as response data.
  • 7. Callback Commands: Client Side Wrapper for additional javascript Method attached to 'Drupal.AjaxCommands.prototype' object Takes 3 arguments ajax response status
  • 8. Anatomy of a Callback Command: JavaScript 01 /** 02 * [commandName description] 03 * 04 * @param {Drupal.Ajax} [ajax] 05 * @param {object} response 06 * @param {number} [status] 07 */ 08 Drupal.AjaxCommands.prototype.[commandName] = function(ajax, response, status){ 09 10 // Custom javascript goes here ... 11 12 } Callback Command needs to be attached as a method to the Drupal.AjaxCommands.prototype object (line #8). Command accepts three arguments and is a wrapper for additional javascript.
  • 10. How to Use Callback Commands Attach Drupal Ajax library to the requesting page Create a callback method that returns an AjaxResponse object Attach commands to AjaxResponse object using 'addCommand'
  • 11. Example: The "Remove" Command Example of using the remove callback command. Link triggers ajax request which returns response with 'remove' command targeting image id.
  • 12. 01 namespace Drupalremove_exampleController; 02 use DrupalCoreControllerControllerBase; 03 04 class RemoveExampleController extends ControllerBase { 05 06 // Return output for displaying an image and ajax link for removing it. 07 public static function demo() { 08 $output['description']['#markup'] = '<p>' . t('The following is an example of using 09 // ... 10 // Attach the ajax library. 11 $output['#attached']['library'][] = 'core/drupal.ajax'; 12 // Return render array 13 return $output; 14 } 15 // ... 16 } remove_example/src/Controller/RemoveExampleController.php Pages that want to use Ajax need to include the ajax library. On line #11 attaching the core Drupal Ajax library to the render array for the page.
  • 13. 01 namespace Drupalremove_exampleController; 02 use DrupalCoreControllerControllerBase; 03 use DrupalCoreAjaxAjaxResponse; 04 use DrupalCoreAjaxRemoveCommand; 05 06 class RemoveExampleController extends ControllerBase { 07 // ... 08 /** 09 * Callback method for removing image from 'remove-example' page. 10 * 11 * @return DrupalCoreAjaxAjaxResponse|mixed 12 */ 13 public static function removeImage() { 14 // Create an Ajax Response object. 15 $response = new AjaxResponse(); 16 // Add a remove command. 17 $response->addCommand(new RemoveCommand('#example_remove_wrapper')); 18 // Return the response object. 19 return $response; 20 } 21 } remove_example/src/Controller/RemoveExampleController.php Classes used for Ajax requests need to include needed classes (line #3, Line #4). Callback method needs to return an ajax command (line #14) and attach commands using 'addCommand' method (line #16).
  • 14. To Use Callback Commands... Attach Drupal Ajax library to the requesting page Create callback method that returns AjaxResponse Attach commands to AjaxResponse object with 'addCommand'
  • 15. Creating Custom Callback Commands Requires a custom module Need to define custom php classes Need to define custom javascript methods
  • 16. Custom Callback Commands: PHP Follow naming convention [CommandName]Command(.php) Implement CommandInterface Define a 'render' method Return an associative array with 'command' element Place in 'src/Ajax/' directory of module
  • 17. Example: SlideRemoveCommand 01 namespace Drupalremove_exampleAjax; 02 03 use DrupalCoreAjaxCommandInterface; 04 // An AJAX command for calling the jQuery slideUp() and remove() methods. 05 class SlideRemoveCommand implements CommandInterface { 06 // Constructs an SlideRemoveCommand object. 07 public function __construct($selector, $duration = NULL) { 08 $this->selector = $selector; 09 $this->duration = $duration; 10 } 11 // Implements DrupalCoreAjaxCommandInterface:render(). 12 public function render() { 13 return array( 14 'command' => 'slideRemove', 15 'selector' => $this->selector, 16 'duration' => $this->duration, 17 ); 18 } 19 } remove_example/src/Ajax/SlideRemoveCommand.php An example of creating a custom 'SlideRemove' callback command PHP Class. Class follows naming conventions and implements CommandInterface (line #5). Defines a render method (line #12), which returns an associative array with a 'command' keyed element. (lines #13 ­ #17).
  • 18. Custom Callback Commands: JavaScript Attach method to 'Drupal.AjaxCommands.prototype' object Take 3 arguments ajax response status Add JavaScript to a custom library
  • 19. Example: slideRemove 01 (function ($, window, Drupal, drupalSettings) { 02 'use strict'; 03 // Command to slide up content before removing it from the page. 04 Drupal.AjaxCommands.prototype.slideRemove = function(ajax, response, status){ 05 var duration = response.duration ? response.duration : "slow"; 06 07 $(response.selector).each(function() { 08 $(this).slideUp(duration, function() { 09 $(this).remove(); 10 }); 11 }); 12 } 13 })(jQuery, this, Drupal, drupalSettings); remove_example/js/ajax.js An example of creating a custom 'slideRemove' callback command javascript method. Attached to 'Drupal.AjaxCommands.prototype' object and accepts three arguments (line #4). Uses response data for additional javascript functionality (lines #5 ­ #13).
  • 20. Example: remove_example/remove-example library 01 remove-example: 02 version: VERSION 03 js: 04 js/ajax.js: {} 05 dependencies: 06 - core/drupal.ajax remove_example.libraries.yml Javascript file that contains custom 'slideRemove' command is added to a library deffinition (lines #3 ­ #4). Add core Drupal Ajax library as a dependency so that it is included (lines #5 ­ #6).
  • 21. To Create Custom Callback Commands... Use a custom module Define classes that implements CommandInterface Attach JavaScript method(s) to 'Drupal.AjaxCommands.prototype'
  • 22. Using Custom Callback Commands Attach custom library to the requesting page Attach commands to AjaxResponse object with 'addCommand'
  • 23. Example: The "slideRemove" Command Example of using the custom slideRemove callback command. Link triggers ajax request which returns response with 'slideRemove' command targeting image id.
  • 24. 01 namespace Drupalremove_exampleController; 02 use DrupalCoreControllerControllerBase; 03 04 class RemoveExampleController extends ControllerBase { 05 06 // Return output for displaying an image and ajax link for removing it. 07 public static function demo() { 08 $output['description']['#markup'] = '<p>' . t('The following is an example of using 09 // ... 10 // Attach custom Ajax command library. 11 $output['#attached']['library'][] = 'remove_example/remove-example'; 12 // Return render array 13 return $output; 14 } 15 // ... 16 } remove_example/src/Controller/RemoveExampleController.php Custom Javascript library needs to be included on requesting page, so that methods are attached. Attaching library to render array on line #11.
  • 25. 01 namespace Drupalremove_exampleController; 02 use DrupalCoreControllerControllerBase; 03 use DrupalCoreAjaxAjaxResponse; 04 use DrupalCoreremove_exampleSlideRemoveCommand; 05 06 class RemoveExampleController extends ControllerBase { 07 // ... 08 /** 09 * Callback method for removing image from 'remove-example' page. 10 * 11 * @return DrupalCoreAjaxAjaxResponse|mixed 12 */ 13 public static function removeImage() { 14 // Create an Ajax Response object. 15 $response = new AjaxResponse(); 16 // Add a remove command. 17 $response->addCommand(new SlideRemoveCommand('#example_remove_wrapper', 'slow' 18 // Return the response object. 19 return $response; 20 } 21 } remove_example/src/Controller/RemoveExampleController.php Like core callback commands, custom command classes have to be included in callback controller (line #4) and added to AjaxResponse in callback method (line #17).
  • 26. To Use Custom Callback Commands... Attach custom library to the requesting page Attach commands to AjaxResponse object with 'addCommand'
  • 28. AJAX Callback Commands Are... Functions returned and invoked by all Ajax responses PHP Classes implementing CommandInterface Methods attached to 'Drupal.AjaxCommands.prototype' object
  • 29. To Use AJAX Callback Commands... Attach Drupal Ajax library to the requesting page Create callback method that returns AjaxResponse Attach commands to AjaxResponse object with 'addCommand'
  • 30. To Create AJAX Callback Commands... Use a custom module Define classes that implements CommandInterface Attach JavaScript methods to 'Drupal.AjaxCommands.prototype'
  • 31. To Use Custom AJAX Callback Commands... Attach custom library to the requesting page Same process as using core commands