KEMBAR78
Drupal & javascript | PDF
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

Drupal & javascript

  • 1.
    Drupal & javascript { Javascript developing with Drupal
  • 2.
  • 5.
    What are wegoing 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.jsis 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 wedefine 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 definea new behavior? Drupal.behaviors.behaviorName = { attach: function (context, settings) { //your function over here } };
  • 11.
  • 12.
    Drupal.locale var args={}; args[“%username”] =“Drupaler”; Drupal.t(“hey %username”, args)
  • 13.
    Managing scripts In Drupal7 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 muchcomplex Options: • Type – file, inline, external, setting • Scope – header or footer • Weight – different than the defaults. • More..
  • 16.
    .info files We canalso 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 Librariesare “master scripts” who help us to build our applications. For example: • jQuery • mooTools • jQuery plugins
  • 19.
    Defining new library Wecan 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 Wecan easily can add our library drupal_add_library(‘system', 'vertical-tabs');
  • 21.
    Using jQuery Since Drupal7 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 namespaceis simple: (function ($) { // All your code here // And now you can use $() instead of jQuery()! }) (jQuery);
  • 23.
    Useful tricks! You canfilter 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, thehtml5 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 SinceDrupal 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 Howit 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: Howit works? $(“my_div”).html(“hello world!”); <Array> <JSON> Ajax <JSON> Javascript js
  • 30.
    Drupal Ajax Framework Howit works? <Array> <JSON> Ajax <JSON> Javascript js
  • 31.
    Drupal Ajax Framework Mainprinciple: “Graceful degradation” If javascript is disabled, the functionality still works well.
  • 32.
    Simple Ajax • Createa 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 weshould 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 weshould 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 weshould 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 weshould 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 weshould 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 weshould 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 Formis 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 shouldadd 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 theform must made in the form builder!
  • 47.
    Using native ajax Wecan 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 Wecan 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 Thenwe 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 Thenwe 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']; }
  • 51.
  • 52.
  • 53.
    Resources & seemore About javascript localization Managing javascript in Drupal 7 JavaScript Theme Functions in Drupal