SlideShare a Scribd company logo
1 of 33
Download to read offline
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
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schemaKiel 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 DDDAleix 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 DevelopmentNuvole
 
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.5Leonardo Proietti
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio 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/09Daniel 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 clienteLeonardo Proietti
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram 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 PerformanceIvan Chepurnyi
 
Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016John 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 zLEDC 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
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
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 archtiecturesIegor Fadieiev
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4JoeDinaso
 
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
 
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 HeavenJoshua 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 CodeSWIFTotter Solutions
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2次世代PHPフレームワーク Symfony2
次世代PHPフレームワーク Symfony2Masao Maeda
 
Scala4sling
Scala4slingScala4sling
Scala4slingday
 
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
 

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 accessibilityMichael Miles
 
How to Foster Team Success
How to Foster Team SuccessHow to Foster Team Success
How to Foster Team SuccessMichael 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 2017Michael 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 2017Michael 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 2017Michael 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 2017Michael Miles
 
INCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond AccessibilityINCLUSIVE DESIGN: Going beyond Accessibility
INCLUSIVE DESIGN: Going beyond AccessibilityMichael Miles
 
The Flexibility of Drupal 8
The Flexibility of Drupal 8The Flexibility of Drupal 8
The Flexibility of Drupal 8Michael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of DrupalMichael 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 ModulesMichael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of DrupalMichael Miles
 
The Flexibility of Drupal
The Flexibility of DrupalThe Flexibility of Drupal
The Flexibility of DrupalMichael 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 modulesMichael 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 2015Michael 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 2014Michael 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

定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 

Recently uploaded (20)

定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 

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