SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
jQuery in Drupal:
overview, tools, how-tos
 DrupalCamp Vancouver 2008
Introduction

• jQuery is a JavaScript Framework

• In core since Drupal 5 (version 1.0.1)

• Modular, like Drupal itself

• and, like Drupal, constantly evolving...
Overview / Timeline
jQuery Syntax Refresher
• Selectors
   – $(‘#myId’), $(‘div.myClass’),
     $(‘li:not(.active)’), $(‘a[href^=“mailto”]’)
• Commands
   – .hide(), .show(), .slideToggle(), .each(), etc
• Utility Functions
   – $.each(), $.get(), $.browser(), $.noConflict()

• Chaining Example
  $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap
  ('<div class=quot;my-wrapperquot;></div>');
Important Functions

• drupal_add_js
  – Add a JavaScript file, setting or inline code to the
    page
  – parameters: data, type, scope, defer, cache
  – Examples:
     • drupal_add_js(drupal_get_path(‘module’,
       ‘mymodule’) .'/myjs.js');
     • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’);
     • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’);
• Use ‘setting’ type to make your module’s
  settings available to js
Important Functions

• drupal_get_js()
  – called from phptemplate.engine (assigned
    to scripts variable)
  – makes a call to drupal_add_js() to get the
    $javascript array
  – $output .= '<script type=quot;text/javascriptquot;>
    Drupal.extend({ settings: '. drupal_to_js
    (call_user_func_array('array_merge_recursive',
    $data)) .quot; });</script>nquot;;
Important Functions

• drupal_to_js()
  – Converts a PHP variable into its JavaScript
    equivalent
  – e.g. convert a PHP array into a JSON object
  – used in the callback function for an AJAX
    path
The Drupal JavaScript Object

 drupal.js in D5:
 var Drupal = Drupal || {};



 drupal.js in D6:

 var Drupal = Drupal || { 'settings': {},
 'behaviors': {}, 'themes': {}, 'locale': {} };
Ajaxifying Drupal with jQuery

• Asynchronous JavaScript and XML
  – retrieve data from the server and load into
    the DOM of the current page without
    refreshing the page
  – $(‘#someDiv’).load(‘/serverResource’);
  – the above corresponds to about 20 lines of
    normal js
• jQuery provides different AJAX
  functions, depending on your needs
Ajaxifying Drupal with jQuery

• jQuery AJAX functions:
  – $(‘#someDiv’).load(url, parameters,
    callback);
  – $.get(url, parameters, callback)
  – $.post(url, parameters, callback)
  – $.ajax(options)
Ajaxifying Drupal with jQuery




                         11
Ajaxifying Drupal with jQuery

• Basic essentials:
  – $.get (or another AJAX method)
  – drupal/path (menu callback)
  – callback function
• drupal_to_js($var)
  – to convert your php array into a JSON
    array
• Drupal.parseJSON(data)
Ajaxifying Drupal with jQuery
                Menu Callback

$items[] = array(
  'path' => 'photostories/get/photos',
  'type' => MENU_CALLBACK,
  'access' => user_access('access content'),
  'callback' => 'kflick_get_photos_ajax'
);
Ajaxifying Drupal with jQuery
                Callback Function

function kflick_get_photos_ajax($nid) {
    $photo = kflick_get_photo($nid);
    $imagefile = theme('image', $photo);
    print drupal_to_js(array(
    'image' => $imagefile,
    )
    );
}
Ajaxifying Drupal with jQuery
Drupal.kflick = function() {
  var imageDetails = function(data) {
    var result = Drupal.parseJson(data);
    $('div.field-type-image div.field-item').html(result['image']);
  }
  $('a.kflick_button').click(function(){
    $('a.kflick_button').removeClass('active');
    $(this).addClass('active');
    $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null,
imageDetails);
    return false;
  });
}

if (Drupal.jsEnabled) {
	

     $(document).ready(Drupal.kflick);
}
Drupal 6: behaviors

• In D6, wrap all your module’s jQuery
  behaviours in a function assigned to
  Drupal.behaviors.mymodule
• no need to call it within
  $(document).ready() as Drupal
  automatically does it for you
• all behaviors can then be reattached to
  DOM elements that have come from an
  AJAX call
Drupal 6: behaviors
Drupal.behaviors.kflick = function(context) {
  $('div.field-type-image:not(.kflick-processed)', context).addClass
(‘kflick-processed’).each(function(){
    var imageDetails = function(data) {
      var result = Drupal.parseJson(data);
      $('div.field-type-image div.field-item').html(result['image']);
    }
    $('a.kflick_button').click(function(){
      $('a.kflick_button').removeClass('active');
      $(this).addClass('active');
      $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt
(this.id, 10), null, imageDetails);
      return false;
    });
  });
}
Drupal 6: behaviors
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
       jQuery.each(Drupal.behaviors,
   function() {
      this(context);
    });
  }
};
What is AHAH?

• Asynchronous HTML and HTTP
• still uses the XMLHttpRequest object
• still uses JavaScript
• loads html content retrieved from the
  server directly into the DOM - no
  parsing necessary
• AHAH in Drupal = AHAH Forms
• AHAH Forms Framework module
• In core as of D6
AHAH in Drupal 6
  $form['qt_wrapper']['tabs_more'] = array(
     '#type' => 'submit',
     '#value' => t('More tabs'),
     '#description' => t(quot;Click here to add more tabs.quot;),
     '#weight' => 1,
     '#submit' => array('qt_more_tabs_submit'), // If no
javascript action.
     '#ahah' => array(
        'path' => 'quicktabs/ahah',
        'wrapper' => 'quicktabs-tabs',
        'method' => 'replace',
        'effect' => 'fade',
     ),
  );
Drag & Drop
drupal_add_tabledrag($table_id, $action, $relationship, $group);

theme('table', $header, $rows, array('id' => 'my-table'));

$form['my_elements'][$delta]['weight']['#attributes']
['class'] = quot;my-elements-weightquot;;

$row = array(...);
$rows[] = array(
'data' => $row,
'class' => 'draggable',
);

drupal_add_tabledrag('my-module-table', 'order',
'sibling', 'my-elements-weight');
Resources

• JavaScript Startup Guide
  on api.drupal.org
• drupaldojo.com/lesson/ahah
• http://jquery.com
• Firebug console
• Books
  – Learning jQuery
  – jQuery in Action

Mais conteúdo relacionado

Mais procurados

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Krista Thomas
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7Michael Milz
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinADCI Solutions
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jeresig
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)jeresig
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.xJoão Ventura
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationMevin Mohan
 
JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)jeresig
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)JavaScript Libraries (@Media)
JavaScript Libraries (@Media)jeresig
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...DicodingEvent
 
AngularJS first steps
AngularJS first stepsAngularJS first steps
AngularJS first stepsseges
 

Mais procurados (20)

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton Shubkin
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
BackboneJs
BackboneJsBackboneJs
BackboneJs
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.x
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)JavaScript Libraries (@Media)
JavaScript Libraries (@Media)
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
AngularJS first steps
AngularJS first stepsAngularJS first steps
AngularJS first steps
 

Destaque

Destaque (8)

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

Semelhante a JQuery In Drupal

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryRemy Sharp
 
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
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
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
 
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
 
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
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Анатолий Поляков - 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
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuerydeimos
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)jeresig
 
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
 

Semelhante a JQuery In Drupal (20)

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
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
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
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
 
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
 
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
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Анатолий Поляков - 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
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
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
 

Último

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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

JQuery In Drupal

  • 1. jQuery in Drupal: overview, tools, how-tos DrupalCamp Vancouver 2008
  • 2. Introduction • jQuery is a JavaScript Framework • In core since Drupal 5 (version 1.0.1) • Modular, like Drupal itself • and, like Drupal, constantly evolving...
  • 4. jQuery Syntax Refresher • Selectors – $(‘#myId’), $(‘div.myClass’), $(‘li:not(.active)’), $(‘a[href^=“mailto”]’) • Commands – .hide(), .show(), .slideToggle(), .each(), etc • Utility Functions – $.each(), $.get(), $.browser(), $.noConflict() • Chaining Example $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap ('<div class=quot;my-wrapperquot;></div>');
  • 5. Important Functions • drupal_add_js – Add a JavaScript file, setting or inline code to the page – parameters: data, type, scope, defer, cache – Examples: • drupal_add_js(drupal_get_path(‘module’, ‘mymodule’) .'/myjs.js'); • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’); • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’); • Use ‘setting’ type to make your module’s settings available to js
  • 6. Important Functions • drupal_get_js() – called from phptemplate.engine (assigned to scripts variable) – makes a call to drupal_add_js() to get the $javascript array – $output .= '<script type=quot;text/javascriptquot;> Drupal.extend({ settings: '. drupal_to_js (call_user_func_array('array_merge_recursive', $data)) .quot; });</script>nquot;;
  • 7. Important Functions • drupal_to_js() – Converts a PHP variable into its JavaScript equivalent – e.g. convert a PHP array into a JSON object – used in the callback function for an AJAX path
  • 8. The Drupal JavaScript Object drupal.js in D5: var Drupal = Drupal || {}; drupal.js in D6: var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
  • 9. Ajaxifying Drupal with jQuery • Asynchronous JavaScript and XML – retrieve data from the server and load into the DOM of the current page without refreshing the page – $(‘#someDiv’).load(‘/serverResource’); – the above corresponds to about 20 lines of normal js • jQuery provides different AJAX functions, depending on your needs
  • 10. Ajaxifying Drupal with jQuery • jQuery AJAX functions: – $(‘#someDiv’).load(url, parameters, callback); – $.get(url, parameters, callback) – $.post(url, parameters, callback) – $.ajax(options)
  • 12. Ajaxifying Drupal with jQuery • Basic essentials: – $.get (or another AJAX method) – drupal/path (menu callback) – callback function • drupal_to_js($var) – to convert your php array into a JSON array • Drupal.parseJSON(data)
  • 13. Ajaxifying Drupal with jQuery Menu Callback $items[] = array( 'path' => 'photostories/get/photos', 'type' => MENU_CALLBACK, 'access' => user_access('access content'), 'callback' => 'kflick_get_photos_ajax' );
  • 14. Ajaxifying Drupal with jQuery Callback Function function kflick_get_photos_ajax($nid) { $photo = kflick_get_photo($nid); $imagefile = theme('image', $photo); print drupal_to_js(array( 'image' => $imagefile, ) ); }
  • 15. Ajaxifying Drupal with jQuery Drupal.kflick = function() { var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null, imageDetails); return false; }); } if (Drupal.jsEnabled) { $(document).ready(Drupal.kflick); }
  • 16. Drupal 6: behaviors • In D6, wrap all your module’s jQuery behaviours in a function assigned to Drupal.behaviors.mymodule • no need to call it within $(document).ready() as Drupal automatically does it for you • all behaviors can then be reattached to DOM elements that have come from an AJAX call
  • 17. Drupal 6: behaviors Drupal.behaviors.kflick = function(context) { $('div.field-type-image:not(.kflick-processed)', context).addClass (‘kflick-processed’).each(function(){ var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt (this.id, 10), null, imageDetails); return false; }); }); }
  • 18. Drupal 6: behaviors Drupal.attachBehaviors = function(context) { context = context || document; if (Drupal.jsEnabled) { // Execute all of them. jQuery.each(Drupal.behaviors, function() { this(context); }); } };
  • 19. What is AHAH? • Asynchronous HTML and HTTP • still uses the XMLHttpRequest object • still uses JavaScript • loads html content retrieved from the server directly into the DOM - no parsing necessary • AHAH in Drupal = AHAH Forms • AHAH Forms Framework module • In core as of D6
  • 20. AHAH in Drupal 6 $form['qt_wrapper']['tabs_more'] = array( '#type' => 'submit', '#value' => t('More tabs'), '#description' => t(quot;Click here to add more tabs.quot;), '#weight' => 1, '#submit' => array('qt_more_tabs_submit'), // If no javascript action. '#ahah' => array( 'path' => 'quicktabs/ahah', 'wrapper' => 'quicktabs-tabs', 'method' => 'replace', 'effect' => 'fade', ), );
  • 21. Drag & Drop drupal_add_tabledrag($table_id, $action, $relationship, $group); theme('table', $header, $rows, array('id' => 'my-table')); $form['my_elements'][$delta]['weight']['#attributes'] ['class'] = quot;my-elements-weightquot;; $row = array(...); $rows[] = array( 'data' => $row, 'class' => 'draggable', ); drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  • 22. Resources • JavaScript Startup Guide on api.drupal.org • drupaldojo.com/lesson/ahah • http://jquery.com • Firebug console • Books – Learning jQuery – jQuery in Action