SlideShare uma empresa Scribd logo
1 de 53
Drupal & javascript
 { Javascript developing with Drupal
Who dafuq are you?
What are we going to talk
            about?
1. Introducing to drupal.js

2. Working with javascript libraries and jQuery

3. Using Drupal’s Ajax framework
What is drupal.js
drupal.js is a tool who provided by the Drupal.

It handles with the communication between Drupal to our script.




                                                       js
theme        var   Drupal             other
                                      Drupal.encodePath ()
                                      Drupal.checkPlain()
                                      …




  settings                  local
                            (localization)

              behaviors
Drupal.theme
How do we define a theme?

Dupal.theme.prototype.displayName = function(name, url) {
  return '<a href="' + url + '">' + name + '</a>';
}


How do we use a theme?
Drupal.theme('displayName', name, url);
Drupal.settings
Built-in settings:
   base_path, pathPrefix …


How to define from PHP?
  drupal_add_js( array('myModule' => array('key' => 'value')), 'setting’ );


How we retrieve from javascript?
  Drupal.settings.myModule.key
Drupal.behaviors
How to define a new behavior?
    Drupal.behaviors.behaviorName = {
      attach: function (context, settings) {
          //your function over here
      }
    };
Drupal.locale
Drupal.t(string, args)



Drupal.format_plural(count, singlar, palural, args)
Drupal.locale
var args={};
args[“%username”] = “Drupaler”;



Drupal.t(“hey %username”, args)
Managing scripts
In Drupal 7 the type of the scripts splits into three groups:

   1      Library              drupal_add_js()


  2      Module


  3       Theme
                                    *.info
drupal_add_js
drupal_add_js('misc/collapse.js');

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

drupal_add_js('http://example.com/example.js', 'external');
And even much complex
Options:

   • Type – file, inline, external, setting

   • Scope – header or footer

   • Weight – different than the defaults.

   • More..
.info files
We can also add the script in the module and theme .info files:

       scripts[] = somescript.js
Overriding
       We can also override other additions of scripts

function hook_js_alter(&$javascript) {

    $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

}
Working with libraries
Libraries are “master scripts” who help us to build our applications.

For example:

    • jQuery

    • mooTools

    • jQuery plugins
Defining new library
We can define new libraries by the hook_library()
function system_library() {
  …
  $libraries['vertical-tabs'] = array(
     'title'   => 'Vertical Tabs',
     'website' => 'http://drupal.org/node/323112',
     ‘version' => '1.0',
     'js'      => array('misc/vertical-tabs.js' => array()),
     'css'     => array('misc/vertical-tabs.css' => array()),
  );
  return $libraries;
}
Adding a library
We can easily can add our library

        drupal_add_library(‘system', 'vertical-tabs');
Using jQuery
Since Drupal 7 released, we use namespaces!

The namespaces stands to avoiding conflicts with other js library..

                that’s mean we can use other libraries like mooTools!
Using jQuery
Using namespace is simple:



       (function   ($) {
               // All your code here
               // And now you can use $() instead of jQuery()!
       }) (jQuery);
Useful tricks!
You can filter a script by the class!
if($("#node-756722").length) {
         // do something
}




The module context can also help to define specific classes!
Useful tricks!
Also, the html5 standard allows you to store data via the markup! (you can

actually cache Ajax easily!).



We use the “data-*” attribute.

$("#my_changed_div").attr(“data-maximaized", data);
Drupal Ajax Framework
Since Drupal 7, there is a powerful framework in Drupal who handle with Ajax.


The framework originally taken from Chaos Tools(ctools).

It's especially useful for forms.



The idea is “programming only PHP”
Use your PHP to tell javascript what to do.
Drupal Ajax Framework
How it works?




 <Array>        <JSON>   Ajax   <JSON>        Javascript



                                         js
Array of commands:

         Drupal Ajax Framework
              array(
                 'command' =>
                 'method' =>
                                'insert',
                                'html',
                 'selector'=>   '#my_div',
                 'data'    =>   'hello
How it   works?
              world!',
              );




 <Array>              <JSON>         Ajax    <JSON>        Javascript



                                                      js
Drupal Ajax Framework
                { command: ‘insert’, method: ‘html’,
                  selector: ‘#my_div’, data: ‘hello
                              world!’ }
How it works?




 <Array>         <JSON>         Ajax     <JSON>             Javascript



                                                       js
Drupal Ajax FrameworkCommands:
How it works?    $(“my_div”).html(“hello world!”);




 <Array>        <JSON>       Ajax     <JSON>              Javascript



                                                     js
Drupal Ajax Framework
How it works?




 <Array>        <JSON>   Ajax   <JSON>        Javascript



                                         js
Drupal Ajax Framework
Main principle:


                          “Graceful degradation”


If javascript is disabled, the functionality still works well.
Simple Ajax
• Create a simple link
    • Use href for the path of the menu callback
    • Use “use-ajax” class

• Build a menu callback
    • /nojs/ variation – for javascript disabled
    • /ajax/ variation – for ajax loading
Simple Ajax
<a href=“drupal_and_js/nojs/simple_page” class=“use-ajax”>link</a>




You MUST add the ajax library..

   drupal_add_library('system', 'drupal.ajax');
Simple Ajax
Than we should build our menu callback


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Simple Ajax
Than we should build our menu callback


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Simple Ajax
Than we should build our menu callback


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Simple Ajax
Than we should build our menu callback


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Simple Ajax
Than we should build our menu callback
                             $(“#content .content”).html(“Hey I am ajax data!”);


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Simple Ajax
Than we should build our menu callback


function my_simple_page($js) {
  if($js=="ajax") {
    $cmds   = array();
    $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!");
    return array('#type'=>'ajax', '#commands'=>$cmds);
  } else
    return "Hello no-js!";
}
Ajax Forms
Ajax Form is a integrally of the Drupal form API.



Every Ajax request the whole form is rebuilt.

The callback retrieves only the changed part.
Ajax Forms
We should add a #ajax parameter to the element who call the ajax.

In this parameter we will define:

    • PHP callback

    • Wrapper – who will replaced by the JS(an ID of the warpper!)

    • Method – replace, html, etc..

    • Path, effect, event, and much more..
Ajax Forms
$form['select_number'] = array(
  '#type' => 'select',
  '#ajax' => array(
     'callback' => 'my_simple_ajax_callback',
     'wrapper' => 'text_div',
     'method'   => 'html',
  ),
  …
)

$form['text_place'] = array(
    "#markup" => t("You choose @number", $args),
    "#prefix" => '<div id="text_div">',
    "#suffix" => '</div>',
);
Ajax Forms
$form['select_number'] = array(
  '#type' => 'select',
  '#ajax' => array(
     'callback' => 'my_simple_ajax_callback',
     'wrapper' => 'text_div',
     'method'   => 'html',
  ),
  …
)

$form['text_place'] = array(
    "#markup" => t("You choose @number", $args),
    "#prefix" => '<div id="text_div">',
    "#suffix" => '</div>',
);
Ajax Forms
function my_simple_ajax_callback($form, $form_state) {
  return $form['text_place'];
}
Ajax Forms
function my_simple_ajax_callback($form, $form_state) {
  return $form['text_place'];
}



$form['text_place'] = array(
    "#markup" => t("You choose @number", $args),
    "#prefix" => '<div id="text_div">',
    "#suffix" => '</div>',
);
Notice!
Changes to the form must made in the form builder!
Using native ajax
We can call to an ajax script without the Ajax framework by defining it

within the hook_theme:

 function myhook_menu() {
   return array(
       'ajax/node/%node' => array(
         …
         'delivery callback' => 'ajax_deliver',
         …
   );
 )
Using native ajax
We can call to an ajax script without the Ajax framework by defining it

within the hook_theme:

 function myhook_menu() {
   return array(
       'ajax/node/%node' => array(
         …
         'delivery callback' => 'ajax_deliver',
         …
   );
 )
Using native ajax
Then we can access it via the Ajax:

var ajax_url =
Drupal.settings.basePath+Drupal.encodePath("ajax/node/11");

$.getJSON(ajax_url, function(json) {
  var data=json[1]['data'];
}
Using native ajax
Then we can access it via the Ajax:

var ajax_url =
Drupal.settings.basePath+Drupal.encodePath("ajax/node/11");

$.getJSON(ajax_url, function(json) {
  var data=json[1]['data'];
}
Questions?
Thank you!
Resources & see more
About javascript localization

Managing javascript in Drupal 7

JavaScript Theme Functions in Drupal

Mais conteúdo relacionado

Mais procurados

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 

Mais procurados (19)

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Drupal.js: Best Practices for Managing Javascript in Drupal
Drupal.js: Best Practices for Managing Javascript in DrupalDrupal.js: Best Practices for Managing Javascript in Drupal
Drupal.js: Best Practices for Managing Javascript in Drupal
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
jQuery
jQueryjQuery
jQuery
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Ajax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsAjax nested form and ajax upload in rails
Ajax nested form and ajax upload in rails
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web Components
 
Jquery
JqueryJquery
Jquery
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 

Semelhante a Drupal & javascript

Анатолий Поляков - 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
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
adamlogic
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua
 
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
Paulo Ragonha
 

Semelhante a Drupal & javascript (20)

Анатолий Поляков - 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
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuery
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback Commands
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
NYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback CommandsNYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
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
 

Mais de Almog Baku

Mais de Almog Baku (7)

gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and Golang
 
Symfony2 form type
Symfony2 form typeSymfony2 form type
Symfony2 form type
 
Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2Build REST APIs like a Jedi with Symfony2
Build REST APIs like a Jedi with Symfony2
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
 
Turbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassTurbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & Compass
 
Wordpress optimization
Wordpress optimizationWordpress optimization
Wordpress optimization
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 

Drupal & javascript

  • 1. Drupal & javascript { Javascript developing with Drupal
  • 3.
  • 4.
  • 5. What are we going to talk about? 1. Introducing to drupal.js 2. Working with javascript libraries and jQuery 3. Using Drupal’s Ajax framework
  • 6. What is drupal.js drupal.js is a tool who provided by the Drupal. It handles with the communication between Drupal to our script. js
  • 7. theme var Drupal other Drupal.encodePath () Drupal.checkPlain() … settings local (localization) behaviors
  • 8. Drupal.theme How do we define a theme? Dupal.theme.prototype.displayName = function(name, url) { return '<a href="' + url + '">' + name + '</a>'; } How do we use a theme? Drupal.theme('displayName', name, url);
  • 9. Drupal.settings Built-in settings: base_path, pathPrefix … How to define from PHP? drupal_add_js( array('myModule' => array('key' => 'value')), 'setting’ ); How we retrieve from javascript? Drupal.settings.myModule.key
  • 10. Drupal.behaviors How to define a new behavior? Drupal.behaviors.behaviorName = { attach: function (context, settings) { //your function over here } };
  • 12. Drupal.locale var args={}; args[“%username”] = “Drupaler”; Drupal.t(“hey %username”, args)
  • 13. Managing scripts In Drupal 7 the type of the scripts splits into three groups: 1 Library drupal_add_js() 2 Module 3 Theme *.info
  • 14. drupal_add_js drupal_add_js('misc/collapse.js'); drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline'); drupal_add_js('http://example.com/example.js', 'external');
  • 15. And even much complex Options: • Type – file, inline, external, setting • Scope – header or footer • Weight – different than the defaults. • More..
  • 16. .info files We can also add the script in the module and theme .info files: scripts[] = somescript.js
  • 17. Overriding We can also override other additions of scripts function hook_js_alter(&$javascript) { $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; }
  • 18. Working with libraries Libraries are “master scripts” who help us to build our applications. For example: • jQuery • mooTools • jQuery plugins
  • 19. Defining new library We can define new libraries by the hook_library() function system_library() { … $libraries['vertical-tabs'] = array( 'title' => 'Vertical Tabs', 'website' => 'http://drupal.org/node/323112', ‘version' => '1.0', 'js' => array('misc/vertical-tabs.js' => array()), 'css' => array('misc/vertical-tabs.css' => array()), ); return $libraries; }
  • 20. Adding a library We can easily can add our library drupal_add_library(‘system', 'vertical-tabs');
  • 21. Using jQuery Since Drupal 7 released, we use namespaces! The namespaces stands to avoiding conflicts with other js library.. that’s mean we can use other libraries like mooTools!
  • 22. Using jQuery Using namespace is simple: (function ($) { // All your code here // And now you can use $() instead of jQuery()! }) (jQuery);
  • 23. Useful tricks! You can filter a script by the class! if($("#node-756722").length) { // do something } The module context can also help to define specific classes!
  • 24. Useful tricks! Also, the html5 standard allows you to store data via the markup! (you can actually cache Ajax easily!). We use the “data-*” attribute. $("#my_changed_div").attr(“data-maximaized", data);
  • 25. Drupal Ajax Framework Since Drupal 7, there is a powerful framework in Drupal who handle with Ajax. The framework originally taken from Chaos Tools(ctools). It's especially useful for forms. The idea is “programming only PHP” Use your PHP to tell javascript what to do.
  • 26. Drupal Ajax Framework How it works? <Array> <JSON> Ajax <JSON> Javascript js
  • 27. Array of commands: Drupal Ajax Framework array( 'command' => 'method' => 'insert', 'html', 'selector'=> '#my_div', 'data' => 'hello How it works? world!', ); <Array> <JSON> Ajax <JSON> Javascript js
  • 28. Drupal Ajax Framework { command: ‘insert’, method: ‘html’, selector: ‘#my_div’, data: ‘hello world!’ } How it works? <Array> <JSON> Ajax <JSON> Javascript js
  • 29. Drupal Ajax FrameworkCommands: How it works? $(“my_div”).html(“hello world!”); <Array> <JSON> Ajax <JSON> Javascript js
  • 30. Drupal Ajax Framework How it works? <Array> <JSON> Ajax <JSON> Javascript js
  • 31. Drupal Ajax Framework Main principle: “Graceful degradation” If javascript is disabled, the functionality still works well.
  • 32. Simple Ajax • Create a simple link • Use href for the path of the menu callback • Use “use-ajax” class • Build a menu callback • /nojs/ variation – for javascript disabled • /ajax/ variation – for ajax loading
  • 33. Simple Ajax <a href=“drupal_and_js/nojs/simple_page” class=“use-ajax”>link</a> You MUST add the ajax library.. drupal_add_library('system', 'drupal.ajax');
  • 34. Simple Ajax Than we should build our menu callback function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 35. Simple Ajax Than we should build our menu callback function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 36. Simple Ajax Than we should build our menu callback function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 37. Simple Ajax Than we should build our menu callback function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 38. Simple Ajax Than we should build our menu callback $(“#content .content”).html(“Hey I am ajax data!”); function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 39. Simple Ajax Than we should build our menu callback function my_simple_page($js) { if($js=="ajax") { $cmds = array(); $cmds[] = ajax_command_html("#content .content", "Hey I am ajax data!"); return array('#type'=>'ajax', '#commands'=>$cmds); } else return "Hello no-js!"; }
  • 40. Ajax Forms Ajax Form is a integrally of the Drupal form API. Every Ajax request the whole form is rebuilt. The callback retrieves only the changed part.
  • 41. Ajax Forms We should add a #ajax parameter to the element who call the ajax. In this parameter we will define: • PHP callback • Wrapper – who will replaced by the JS(an ID of the warpper!) • Method – replace, html, etc.. • Path, effect, event, and much more..
  • 42. Ajax Forms $form['select_number'] = array( '#type' => 'select', '#ajax' => array( 'callback' => 'my_simple_ajax_callback', 'wrapper' => 'text_div', 'method' => 'html', ), … ) $form['text_place'] = array( "#markup" => t("You choose @number", $args), "#prefix" => '<div id="text_div">', "#suffix" => '</div>', );
  • 43. Ajax Forms $form['select_number'] = array( '#type' => 'select', '#ajax' => array( 'callback' => 'my_simple_ajax_callback', 'wrapper' => 'text_div', 'method' => 'html', ), … ) $form['text_place'] = array( "#markup" => t("You choose @number", $args), "#prefix" => '<div id="text_div">', "#suffix" => '</div>', );
  • 44. Ajax Forms function my_simple_ajax_callback($form, $form_state) { return $form['text_place']; }
  • 45. Ajax Forms function my_simple_ajax_callback($form, $form_state) { return $form['text_place']; } $form['text_place'] = array( "#markup" => t("You choose @number", $args), "#prefix" => '<div id="text_div">', "#suffix" => '</div>', );
  • 46. Notice! Changes to the form must made in the form builder!
  • 47. Using native ajax We can call to an ajax script without the Ajax framework by defining it within the hook_theme: function myhook_menu() { return array( 'ajax/node/%node' => array( … 'delivery callback' => 'ajax_deliver', … ); )
  • 48. Using native ajax We can call to an ajax script without the Ajax framework by defining it within the hook_theme: function myhook_menu() { return array( 'ajax/node/%node' => array( … 'delivery callback' => 'ajax_deliver', … ); )
  • 49. Using native ajax Then we can access it via the Ajax: var ajax_url = Drupal.settings.basePath+Drupal.encodePath("ajax/node/11"); $.getJSON(ajax_url, function(json) { var data=json[1]['data']; }
  • 50. Using native ajax Then we can access it via the Ajax: var ajax_url = Drupal.settings.basePath+Drupal.encodePath("ajax/node/11"); $.getJSON(ajax_url, function(json) { var data=json[1]['data']; }
  • 53. Resources & see more About javascript localization Managing javascript in Drupal 7 JavaScript Theme Functions in Drupal