SlideShare una empresa de 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

Más contenido relacionado

La actualidad más candente

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
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 DrupalBryan Braun
 
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 knowkatbailey
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
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 CairoMohamed Mosaad
 
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 railsTse-Ching Ho
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web ComponentsFelix Arntz
 
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 javascriptThéodore Biadala
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupalBlackCatWeb
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testingsmontanari
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 

La actualidad más candente (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 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 zLEDC 2016
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
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 2016Nicolás Bouhid
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
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 knowWork at Play
 
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 jQuerykatbailey
 
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 JavaScriptGuy Royse
 
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 Treeadamlogic
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsMichael Miles
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke 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 2011camp_drupal_ua
 
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 JavascriptDarren Mothersele
 
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 CommandsMichael Miles
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
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 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
 

Más de Almog Baku

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 GolangAlmog Baku
 
Symfony2 form type
Symfony2 form typeSymfony2 form type
Symfony2 form typeAlmog Baku
 
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 Symfony2Almog Baku
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJSAlmog Baku
 
Turbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassTurbo theming: Introduction to Sass & Compass
Turbo theming: Introduction to Sass & CompassAlmog Baku
 
Wordpress optimization
Wordpress optimizationWordpress optimization
Wordpress optimizationAlmog Baku
 

Más 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

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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 2024Rafal Los
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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