SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 

What's hot (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)
 

Similar to 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
 

Similar to 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
 

More from Almog Baku

More from 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
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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