Kamalakannan – 9789989552
sivkannan77@gmail.com
Table of Contents
Functions & methods........................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Update queries...............................................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
MAX(expression)..............................................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Validating Forms.............................................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Submission Callbacks.........................................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Passing values from PHP to Javascript with "Drupal.settings".................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Clearing the theme cache.....................................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Using Newer Versions of jQuery...............................................
Kamalakannan – 9789989552
sivkannan77@gmail.com
Functions for Drupal's Ajax framework.
Drupal's Ajax framework is used to ...
Kamalakannan – 9789989552
sivkannan77@gmail.com
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'aj...
Kamalakannan – 9789989552
sivkannan77@gmail.com
• #ajax['wrapper']: The CSS ID of the area to be replaced by the content r...
Kamalakannan – 9789989552
sivkannan77@gmail.com
the client, which will then iterate over the array and process it like a m...
Kamalakannan – 9789989552
sivkannan77@gmail.com
Drupal’s online documentation is © 2000-2012 by the individual contributor...
Kamalakannan – 9789989552
sivkannan77@gmail.com
General concepts
The Drupal database layer is built atop PHP's PDO library...
Kamalakannan – 9789989552
sivkannan77@gmail.com
<?php
db_set_active($key);
?>
See the next section, Database configuration...
Kamalakannan – 9789989552
sivkannan77@gmail.com
$result = db_query("SELECT nid, title FROM {node}");
?>
Calling db_query()...
Kamalakannan – 9789989552
sivkannan77@gmail.com
<?php
// WRONG:
$result = db_query("SELECT nid, title FROM {node} WHERE ty...
Kamalakannan – 9789989552
sivkannan77@gmail.com
options that direct how the query will behave. There are typically only tw...
Kamalakannan – 9789989552
sivkannan77@gmail.com
$result = db_query("SELECT id, title FROM {example_table}",
array(), array...
Kamalakannan – 9789989552
sivkannan77@gmail.com
Dynamic queries
Dynamic queries refer to queries that are built dynamicall...
Kamalakannan – 9789989552
sivkannan77@gmail.com
make up this query, and more advanced techniques like joins.
<?php
$query ...
Kamalakannan – 9789989552
sivkannan77@gmail.com
$myselect = db_select('mytable')
->fields('mytable')
->condition('myfield'...
Kamalakannan – 9789989552
sivkannan77@gmail.com
As an alternate shorthand, you can use the fields() method to add multiple...
Kamalakannan – 9789989552
sivkannan77@gmail.com
?>
The first line above will add "COUNT(uid) AS uid_count" to the query. T...
Kamalakannan – 9789989552
sivkannan77@gmail.com
Grouping
To group by a given field, use the groupBy() method.
<?php
$query...
Kamalakannan – 9789989552
sivkannan77@gmail.com
instead of condition() and where().
Executing the query
Once the query is ...
Kamalakannan – 9789989552
sivkannan77@gmail.com
Debugging
To examine the SQL query that the query object will build at a p...
Kamalakannan – 9789989552
sivkannan77@gmail.com
// This line executes the Select object, not the extender. The
extender no...
Kamalakannan – 9789989552
sivkannan77@gmail.com
return $this;
}
/**
* Add a new method of our own.
*/
public function orde...
Kamalakannan – 9789989552
sivkannan77@gmail.com
should be an alphanumeric lowercase string, following the same rules as a ...
Kamalakannan – 9789989552
sivkannan77@gmail.com
Meta data
Queries may also have meta data attached to them to provide addi...
Kamalakannan – 9789989552
sivkannan77@gmail.com
// ...
}
?>
There are two important observations to be made regarding hook...
Kamalakannan – 9789989552
sivkannan77@gmail.com
$node = node_load($record->nid);
}
?>
Depending on what the results are ne...
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Drupal guide
Upcoming SlideShare
Loading in...5
×

Drupal guide

1,694

Published on

Drupal Guide

Published in: Career
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,694
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Drupal guide

  1. 1. Kamalakannan – 9789989552 sivkannan77@gmail.com Table of Contents Functions & methods................................................................................................................11 General concepts................................................................................................................................13 Drivers.......................................................................................................................................13 Connections...............................................................................................................................13 Queries......................................................................................................................................14 Statements.................................................................................................................................14 Static queries......................................................................................................................................14 Prefixing....................................................................................................................................15 Placeholders..............................................................................................................................15 Placeholder arrays.....................................................................................................................16 Query options............................................................................................................................16 Fetching into a class...........................................................................................................................17 Dynamic queries.................................................................................................................................19 Table Of Contents..........................................................................................................................19 The Big Picture..............................................................................................................................19 Joins...............................................................................................................................................20 Fields..............................................................................................................................................21 Distinct...........................................................................................................................................22 Expressions....................................................................................................................................22 Ordering.........................................................................................................................................23 Random ordering...........................................................................................................................23 Grouping........................................................................................................................................23 Ranges and Limits.........................................................................................................................24 Table sorting..................................................................................................................................24 Conditionals...................................................................................................................................24 Executing the query.......................................................................................................................24 Count queries.................................................................................................................................25 Debugging......................................................................................................................................25 Extenders............................................................................................................................................25 Using an Extender..........................................................................................................................26 Creating new extenders..................................................................................................................27 Supporting multiple database types...............................................................................................28 Query alteration..................................................................................................................................28 Tagging..........................................................................................................................................28 Meta data........................................................................................................................................29 hook_query_alter().........................................................................................................................30 Result sets...........................................................................................................................................31 Insert queries......................................................................................................................................33 Compact form................................................................................................................................33 Degenerate form............................................................................................................................34 Multi-insert form............................................................................................................................35 Inserting based on the results of a select query ............................................................................36 Default values................................................................................................................................37 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  2. 2. Kamalakannan – 9789989552 sivkannan77@gmail.com Update queries....................................................................................................................................37 Delete queries.....................................................................................................................................38 Merge queries.....................................................................................................................................39 Just set it.........................................................................................................................................39 Conditional set...............................................................................................................................40 Precedence.....................................................................................................................................41 Conditional clauses.............................................................................................................................41 Concepts.........................................................................................................................................41 API.................................................................................................................................................42 Array operators.........................................................................................................................42 Nested conditionals...................................................................................................................43 Null values................................................................................................................................43 Subselects..................................................................................................................................44 Examples........................................................................................................................................44 Transactions........................................................................................................................................45 Chaining.............................................................................................................................................46 Functions and operators......................................................................................................................48 Logical operators...........................................................................................................................49 AND..........................................................................................................................................49 OR.............................................................................................................................................49 NOT..........................................................................................................................................49 Comparison operators....................................................................................................................49 <................................................................................................................................................49 >................................................................................................................................................49 <=..............................................................................................................................................49 >=..............................................................................................................................................49 <>..............................................................................................................................................49 LIKE..........................................................................................................................................49 Type manipulation operators.........................................................................................................49 String functions and operators.......................................................................................................49 CONCAT(string1, string2)........................................................................................................49 SUBSTRING(string, from, length)...........................................................................................49 SUBSTRING_INDEX(string, delimiter, count).......................................................................49 LENGTH(string).......................................................................................................................49 Mathematical functions and operators...........................................................................................49 GREATEST(num1, num2)........................................................................................................49 POW(num1, num2)...................................................................................................................50 LOG(base, value)......................................................................................................................50 RAND().....................................................................................................................................50 Date/time functions........................................................................................................................50 Aggregation functions....................................................................................................................50 COUNT(expression).................................................................................................................50 SUM(expression)......................................................................................................................50 AVG(expression).......................................................................................................................50 MIN(expression).......................................................................................................................50 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  3. 3. Kamalakannan – 9789989552 sivkannan77@gmail.com MAX(expression)......................................................................................................................50 A beginner's guide to caching data.....................................................................................................51 Article by Jeff EatonMay 18, 2007 - 7:57pm ......................................................................51 The basics..................................................................................................................................51 Drupal's cache functions...........................................................................................................52 Keeping up to date....................................................................................................................52 Advanced caching.....................................................................................................................53 A few caveats............................................................................................................................53 Go west, young Drupaler!.........................................................................................................54 File API...............................................................................................................................................55 Streamwrapper notation for all files..........................................................................................55 File usage functions............................................................................................................................55 General concepts................................................................................................................................56 What are stream wrappers?..................................................................................................56 "Calling" streams..................................................................................................................56 Limitations............................................................................................................................56 Important Drupal 7 File API Functions..............................................................................................56 PHP File Functions....................................................................................................................57 Example Code...........................................................................................................................57 Writing stream wrappers.....................................................................................................................58 Sample wrapper (foobar://)..................................................................................................58 Stream wrapper registry.......................................................................................................58 Registering wrappers............................................................................................................59 File API changes from Drupal 6 to Drupal 7......................................................................................59 Summary of managed/unmanaged File API changes...........................................................60 file_copy()............................................................................................................................60 file_delete()..........................................................................................................................61 file_save_data()....................................................................................................................61 Form API............................................................................................................................................62 Form API (Drupal 6.x).......................................................................................................................62 Key documents you'll want to consult if you want to learn the Form API for Drupal 6..........62 Below is an outline meant as a step toward develop comprehensive documentation...............62 Beginners guide..................................................................................................................................64 Form builder function...............................................................................................................64 Adding buttons to a form....................................................................................................................65 Adding fields to a form.......................................................................................................................65 Adding markup to form elements.......................................................................................................66 Warning.....................................................................................................................................66 Grouping fields in a form...................................................................................................................66 Grouping in the form array.......................................................................................................67 Adding visual grouping.............................................................................................................68 Uploading files...................................................................................................................................68 Form API Quickstart Guide................................................................................................................70 Creating Forms..............................................................................................................................70 Theming Forms..............................................................................................................................73 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  4. 4. Kamalakannan – 9789989552 sivkannan77@gmail.com Validating Forms............................................................................................................................75 Submitting Forms..........................................................................................................................75 Understanding the Flow.................................................................................................................76 Overview of Form Management (Drupal 6.x)....................................................................................77 Introduction ...................................................................................................................................77 Basic Concepts...............................................................................................................................77 Building Individual Fields (Form API 6.x)........................................................................................78 Examples of Form Elements..............................................................................................................79 Checkbox..................................................................................................................................79 Checkboxes...............................................................................................................................79 Textfield....................................................................................................................................80 More Information...........................................................................................................................80 Textfield that uses autocomplete........................................................................................................80 Prebuilt autocomplete functions....................................................................................................81 Building a custom autocomplete function.....................................................................................81 The form....................................................................................................................................82 Addition to hook_menu............................................................................................................82 Make a call to the Database, D6 Version..................................................................................82 Make a call to the Database, D7 Version..................................................................................83 Security note:............................................................................................................................83 Form workflow across page requests.................................................................................................84 Form without AJAX.......................................................................................................................84 Form with AJAX............................................................................................................................85 Examples............................................................................................................................................87 Adding checkboxes to a table.............................................................................................................87 Drupal 7.x and 8.x.....................................................................................................................87 Step 1: Get the Data..............................................................................................................87 Step 2: Build the Header......................................................................................................88 Step 3: Build the Data..........................................................................................................88 Step 4: The Magic................................................................................................................89 Additional Options...............................................................................................................89 Retrieving the Selected Element..........................................................................................90 Summing it up Entire Code..................................................................................................90 Drupal 6.x..................................................................................................................................91 Administration settings forms............................................................................................................94 Running custom submission handlers.......................................................................................95 Creating Custom Elements Using Drupal 6.x....................................................................................95 Hook Elements...............................................................................................................................95 Element Themes.............................................................................................................................96 Add Form Element to Form...........................................................................................................97 Value callback or form_type_hook_value()...................................................................................98 Process Callback............................................................................................................................99 Afterbuild Callback........................................................................................................................99 Validation Callbacks....................................................................................................................100 Rendering Callbacks....................................................................................................................100 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  5. 5. Kamalakannan – 9789989552 sivkannan77@gmail.com Submission Callbacks..................................................................................................................100 Redirect after Form Submission.......................................................................................................101 References...............................................................................................................................101 Tutorial: Ten Step-by-Step Code Samples for Learning Form API..................................................101 1. Basic Form....................................................................................................................................102 Code sample #1:......................................................................................................................102 2. Basic Form with submit button....................................................................................................103 Code sample #2:......................................................................................................................103 3. Basic Form with fieldsets.............................................................................................................104 Code sample #3:......................................................................................................................104 4. Basic Form with Fieldsets and validation....................................................................................105 Code sample #4:......................................................................................................................105 5. Basic Form with additional element attributes.............................................................................106 Code sample #5:......................................................................................................................106 6. Basic form with validate handler..................................................................................................108 Code sample #6:......................................................................................................................108 7. Basic form with submit handler....................................................................................................110 Code sample #7:......................................................................................................................110 8. Basic form with button validation................................................................................................111 Code sample #8:......................................................................................................................111 9. Basic form with button form state check......................................................................................114 Code sample #9:......................................................................................................................114 10. Multistep form............................................................................................................................118 Code sample #10:....................................................................................................................118 Display a confirmation message before processing a form..............................................................123 Code samples: displaying the right forms ...................................................................................124 Code samples: processing the form ............................................................................................125 Inner workings..................................................................................................................................126 Creating a "builder" function to generate a form.............................................................................126 Form API Internal Workflow Illustration.........................................................................................127 Forms API - Modify Forms with hook_form_alter() (Drupal 7.x)...................................................127 Drupal 7 JavaScript API...................................................................................................................129 AJAX Forms in Drupal 7.................................................................................................................129 Introduction to AJAX-enabled Forms..........................................................................................129 The Big Idea.................................................................................................................................130 The Basics....................................................................................................................................130 In more detail...............................................................................................................................132 Details and Warnings...................................................................................................................133 Graceful degradation when the browser does not support Javascript..........................................134 More extensive AJAX features....................................................................................................134 Additional resources....................................................................................................................135 Managing JavaScript in Drupal 7.....................................................................................................135 Weighted JavaScript................................................................................................................135 Adding JavaScript in the module's .info file...........................................................................135 External JavaScript.................................................................................................................136 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  6. 6. Kamalakannan – 9789989552 sivkannan77@gmail.com Passing values from PHP to Javascript with "Drupal.settings"..............................................136 Overriding JavaScript.............................................................................................................136 JavaScript Libraries.................................................................................................................136 Prefer drupal_add_library() and always use it for core JavaScript files.................................137 Using jQuery...........................................................................................................................137 Behaviors................................................................................................................................137 jQuery Once method for applying JavaScript behaviors once................................................138 Render Arrays in Drupal 7................................................................................................................139 What is "rendering"?...............................................................................................................139 What is a render array?...........................................................................................................139 Why was this done?................................................................................................................139 Altering...................................................................................................................................140 How are Render Arrays Related to Elements?........................................................................140 Creating Content As Render Array.........................................................................................140 Examples of Specific Array Types..........................................................................................141 A Sampling of Properties........................................................................................................142 Resources................................................................................................................................143 Theme API........................................................................................................................................145 How the Drupal theme system works...............................................................................................148 Overview of theme files...................................................................................................................148 Drupal 6..............................................................................................................................148 Drupal 7..............................................................................................................................148 Writing theme .info files...................................................................................................................149 Example.......................................................................................................................................150 Theme name requirements...........................................................................................................150 Encoding......................................................................................................................................150 Contents.......................................................................................................................................150 Default .info values..........................................................................................................................156 Assigning content to regions............................................................................................................158 Checking to see if a region is occupied............................................................................................160 Theme settings..................................................................................................................................162 Drupal 7.......................................................................................................................................162 Drupal 6.......................................................................................................................................163 Global Settings.................................................................................................................................163 Integrating color module..................................................................................................................164 Design..........................................................................................................................................164 In Practice....................................................................................................................................165 Schemes..................................................................................................................................165 Images to copy........................................................................................................................166 Fill areas and Gradients...........................................................................................................166 Image slices.............................................................................................................................166 Files.........................................................................................................................................167 Stylesheets (CSS)....................................................................................................................168 Making colors match...............................................................................................................168 PHPTemplate changes.............................................................................................................169 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  7. 7. Kamalakannan – 9789989552 sivkannan77@gmail.com Clearing the theme cache..................................................................................................................170 Creating a sub-theme........................................................................................................................170 Creating a sub-theme..............................................................................................................170 Style sheet inheritance.............................................................................................................171 JavaScript inheritance.............................................................................................................171 Template.php function inheritance..........................................................................................171 Page, node, block and other template (.tpl.php) file inheritance.............................................172 Screen shots, logo and favicon inheritance.............................................................................172 Region inheritance..................................................................................................................172 Features inheritance................................................................................................................172 Color and theme settings inheritance......................................................................................172 Advanced theming............................................................................................................................174 Creating advanced theme settings....................................................................................................174 Adding form widgets for your custom theme settings.................................................................174 Getting the settings’ values in your theme files...........................................................................175 Initializing the default values.......................................................................................................176 Adding additional settings to a new version of your theme........................................................177 Drupal 7.......................................................................................................................................177 Custom theme for custom form 6.x..................................................................................................178 Module.........................................................................................................................................178 mymodule.module: mymodule_menu()..................................................................................179 mymodule.module: myformgene().........................................................................................179 Theme..........................................................................................................................................180 template.php: mytheme_theme().............................................................................................180 template.php: mytheme_preprocess_myformname()..............................................................180 mytemplate.tpl.php..................................................................................................................180 Theming Custom Entities.................................................................................................................181 hook_menu()................................................................................................................................181 Page Callback..............................................................................................................................182 MODULE_theme() Hook............................................................................................................184 The Template File........................................................................................................................185 Theming forms in your theme..........................................................................................................185 template.php............................................................................................................................185 [yourtheme]/templates/forms/commerce-checkout-form-checkout.tpl.php...........................186 Targeting different devices...............................................................................................................186 Adding browser-specific style sheets...............................................................................................186 Drupal 6.......................................................................................................................................186 Drupal 7.......................................................................................................................................187 JavaScript and jQuery.......................................................................................................................188 Adding JavaScript........................................................................................................................188 In .info File..............................................................................................................................188 In template.php........................................................................................................................188 JavaScript closures.......................................................................................................................189 JavaScript behaviors....................................................................................................................190 JavaScript theming.......................................................................................................................192 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  8. 8. Kamalakannan – 9789989552 sivkannan77@gmail.com Using Newer Versions of jQuery......................................................................................................192 Method 1: Using hook_js_alter....................................................................................................193 Method 2: Running 2 versions of jQuery side-by-side - the jQuery noConflict() function........193 The Problem............................................................................................................................193 The Solution............................................................................................................................193 Example: my-theme/page.tpl.php...........................................................................................194 Using noConflict in your scripts.............................................................................................194 Using noConflict in contributed scripts..................................................................................194 jQuery Multi module...............................................................................................................195 Method 3: Using jquery_update module.....................................................................................195 Method 4: Swapping jquery with preprocess page......................................................................195 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  9. 9. Kamalakannan – 9789989552 sivkannan77@gmail.com Functions for Drupal's Ajax framework. Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary. This framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser. When using forms, it can be used with the #ajax property. The #ajax property can be used to bind events to the Ajax framework. By default, #ajax uses 'system/ajax' as its path for submission and thus calls ajax_form_callback() and a defined #ajax['callback'] function. However, you may optionally specify a different path to request or a different callback function to invoke, which can return updated HTML or can also return a richer set of Ajax framework commands. Standard form handling is as follows: • A form element has a #ajax property that includes #ajax['callback'] and omits #ajax['path']. See below about using #ajax['path'] to implement advanced use-cases that require something other than standard form handling. • On the specified element, Ajax processing is triggered by a change to that element. • The browser submits an HTTP POST request to the 'system/ajax' Drupal path. • The menu page callback for 'system/ajax', ajax_form_callback(), calls drupal_process_form() to process the form submission and rebuild the form if necessary. The form is processed in much the same way as if it were submitted without Ajax, with the same #process functions and validation and submission handlers called in either case, making it easy to create Ajax-enabled forms that degrade gracefully when JavaScript is disabled. • After form processing is complete, ajax_form_callback() calls the function named by #ajax['callback'], which returns the form element that has been updated and needs to be returned to the browser, or alternatively, an array of custom Ajax commands. • The page delivery callback for 'system/ajax', ajax_deliver(), renders the element returned by #ajax['callback'], and returns the JSON string created by ajax_render() to the browser. • The browser unserializes the returned JSON string into an array of command objects and executes each command, resulting in the old page content within and including the HTML element specified by #ajax['wrapper'] being replaced by the new content returned by #ajax['callback'], using a JavaScript animation effect specified by #ajax['effect']. A simple example of basic Ajax use from the Examples module follows: function main_page() { return drupal_get_form('ajax_example_simplest'); } function ajax_example_simplest($form, &$form_state) { $form = array(); $form['changethis'] = array( '#type' => 'select', '#options' => array( 'one' => 'one', Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  10. 10. Kamalakannan – 9789989552 sivkannan77@gmail.com 'two' => 'two', 'three' => 'three', ), '#ajax' => array( 'callback' => 'ajax_example_simplest_callback', 'wrapper' => 'replace_textfield_div', ), ); // This entire form element will be replaced with an updated value. $form['replace_textfield'] = array( '#type' => 'textfield', '#title' => t("The default value will be changed"), '#description' => t("Say something about why you chose") . "'" . (!empty($form_state['values']['changethis']) ? $form_state['values']['changethis'] : t("Not changed yet")) . "'", '#prefix' => '<div id="replace_textfield_div">', '#suffix' => '</div>', ); return $form; } function ajax_example_simplest_callback($form, $form_state) { // The form has already been submitted and updated. We can return the replaced // item as it is. return $form['replace_textfield']; } In the above example, the 'changethis' element is Ajax-enabled. The default #ajax['event'] is 'change', so when the 'changethis' element changes, an Ajax call is made. The form is submitted and reprocessed, and then the callback is called. In this case, the form has been automatically built changing $form['replace_textfield']['#description'], so the callback just returns that part of the form. To implement Ajax handling in a form, add '#ajax' to the form definition of a field. That field will trigger an Ajax event when it is clicked (or changed, depending on the kind of field). #ajax supports the following parameters (either 'path' or 'callback' is required at least): • #ajax['callback']: The callback to invoke to handle the server side of the Ajax event, which will receive a $form and $form_state as arguments, and returns a renderable array (most often a form or form fragment), an HTML string, or an array of Ajax commands. If returning a renderable array or a string, the value will replace the original element named in #ajax['wrapper'], and theme_status_messages() will be prepended to that element. (If the status messages are not wanted, return an array of Ajax commands instead.) #ajax['wrapper']. If an array of Ajax commands is returned, it will be executed by the calling code. • #ajax['path']: The menu path to use for the request. This is often omitted and the default is used. This path should map to a menu page callback that returns data using ajax_render(). Defaults to 'system/ajax', which invokes ajax_form_callback(), eventually calling the function named in #ajax['callback']. If you use a custom path, you must set up the menu entry and handle the entire callback in your own code. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  11. 11. Kamalakannan – 9789989552 sivkannan77@gmail.com • #ajax['wrapper']: The CSS ID of the area to be replaced by the content returned by the #ajax['callback'] function. The content returned from the callback will replace the entire element named by #ajax['wrapper']. The wrapper is usually created using #prefix and #suffix properties in the form. Note that this is the wrapper ID, not a CSS selector. So to replace the element referred to by the CSS selector #some-selector on the page, use #ajax['wrapper'] = 'some-selector', not '#some-selector'. • #ajax['effect']: The jQuery effect to use when placing the new HTML. Defaults to no effect. Valid options are 'none', 'slide', or 'fade'. • #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be 'slow', 'fast' or a number in milliseconds which represents the length of time the effect should run. • #ajax['event']: The JavaScript event to respond to. This is normally selected automatically for the type of form widget being used, and is only needed if you need to override the default behavior. • #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior. • #ajax['method']: The jQuery method to use to place the new HTML. Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend', 'before', 'after', or 'html'. See the jQuery manipulators documentation for more information on these methods. • #ajax['progress']: Choose either a throbber or progress bar that is displayed while awaiting a response from the callback, and add an optional message. Possible keys: 'type', 'message', 'url', 'interval'. More information is available in the Form API Reference In addition to using Form API for doing in-form modification, Ajax may be enabled by adding classes to buttons and links. By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately. Similarly, submit buttons can be given the class 'use-ajax-submit'. The form will then be submitted via Ajax to the path specified in the #action. Like the ajax-submit class above, this path will have '/nojs/' replaced with '/ajax/' so that the submit handler can tell if the form was submitted in a degraded state or not. When responding to Ajax requests, the server should do what it needs to do for that request, then create a commands array. This commands array will be converted to a JSON object and returned to Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  12. 12. Kamalakannan – 9789989552 sivkannan77@gmail.com the client, which will then iterate over the array and process it like a macro language. Each command item is an associative array which will be converted to a command object on the JavaScript side. $command_item['command'] is the type of command, e.g. 'alert' or 'replace', and will correspond to a method in the Drupal.ajax[command] space. The command array may contain any other data that the command needs to process, e.g. 'method', 'selector', 'settings', etc. Commands are usually created with a couple of helper functions, so they look like this: $commands = array(); // Replace the content of '#object-1' on the page with 'some html here'. $commands[] = ajax_command_replace('#object-1', 'some html here'); // Add a visual "changed" marker to the '#object-1' element. $commands[] = ajax_command_changed('#object-1'); // Menu 'page callback' and #ajax['callback'] functions are supposed to // return render arrays. If returning an Ajax commands array, it must be // encapsulated in a render array structure. return array('#type' => 'ajax', '#commands' => $commands); When returning an Ajax command array, it is often useful to have status messages rendered along with other tasks in the command array. In that case the the Ajax commands array may be constructed like this: $commands = array(); $commands[] = ajax_command_replace(NULL, $output); $commands[] = ajax_command_prepend(NULL, theme('status_messages')); return array('#type' => 'ajax', '#commands' => $commands); See Ajax framework commands Functions & methods Name Description Name Description ajax_base_page_theme Theme callback for Ajax requests. ajax_deliver Packages and sends the result of a page callback as an Ajax response. ajax_footer Performs end-of-Ajax-request tasks. ajax_form_callback Menu callback; handles Ajax requests for the #ajax Form API property. ajax_get_form Gets a form submitted via #ajax during an Ajax callback. ajax_prepare_response Converts the return value of a page callback into an Ajax commands array. ajax_pre_render_element Adds Ajax information about an element to communicate with JavaScript. ajax_process_form Form element processing handler for the #ajax form property. ajax_render Renders a commands array into JSON. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  13. 13. Kamalakannan – 9789989552 sivkannan77@gmail.com Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  14. 14. Kamalakannan – 9789989552 sivkannan77@gmail.com General concepts The Drupal database layer is built atop PHP's PDO library. PDO provides a unified, object-oriented API for accessing different databases but it does not provide an abstraction for the different dialects of SQL used by different databases. Drivers Because different databases require different sorts of interaction, the Drupal database layer requires a driver for each database type. A driver consists of a series of files located in includes/database/driver, where driver is a string representing the unique key for that driver. In most cases the driver key is the lowercased version of the database name, such as "mysql", "pgsql", or "mycustomdriver". Each driver consists of several classes derived from parent classes in the core database system. These driver-specific classes may override whatever behavior is needed to properly support that database type. Driver-specific classes are always named for their parent class followed by an underscore followed by the driver name. For example, the MySQL specific version of InsertQuery is named InsertQuery_mysql. Connections A connection is an object of class DatabaseConnection, which inherits from the PDO class. Every database to which Drupal connects has a single connection object associated with it. That connection object must be subclassed for each individual driver. To access (and open if necessary) a connection object, use: <?php $conn = Database::getConnection($target, $key); ?> For more information on Target and Connection Key, please see the documentation page on Database configuration. To access the currently active connection, use: <?php $conn = Database::getConnection(); ?> this will get the default target of the active connection. Note that in the vast majority of cases you will not need to request the connection object directly. Rather, the procedural wrappers will do so for you. The only reason you would ever need to access a connection object directly is if you are doing complex manipulation of more than one database and you do not want to change the active database. To set the active connection, use: Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  15. 15. Kamalakannan – 9789989552 sivkannan77@gmail.com <?php db_set_active($key); ?> See the next section, Database configuration, for details of connection keys and targets. Queries A query is an SQL statement that will be sent to a database connection. There are six types of queries supported by the database system: Static, Dynamic, Insert, Update, Delete, and Merge. Some queries are written as SQL string templates (prepared statements) while others use object- oriented query builders. A "query object" refers to an instance of a query builder for one of the various query types. Statements A statement object is the result of a Select query. It will always be of type DatabaseStatement, or possibly a subclass of DatabaseStatement. DatabaseStatement extends the PDOStatement class. Drupal uses prepared statements for all queries. A prepared statement is a template for a query into which values will be inserted for execution. Think of a prepared statement as the SQL equivalent of a function, which is then called with parameters to use. In normal PDO, one must explicitly prepare a statement object and then execute it with certain values bound to placeholders in the query. The statement can then be iterated as a result set. Effectively a statement and a result set are synonymous, but only after a statement has been executed. Drupal does not expose the prepared statement directly. Instead, a module developer will use a query object or a one-off SQL string to execute a query and the statement object for that query is returned. The terms "statement object" and "result set object" are therefore more or less synonymous. Static queries The most common form of query in Drupal is a static query. A static query is one that will be passed to the database nearly verbatim. Only Select queries may be static. Only very simple queries should use the static query mechanism. You should use a dynamic query if you need more complex queries, dynamic query generation or alterability. The internal way to issue a static query is with the query method: <?php $result = $conn->query("SELECT nid, title FROM {node}"); ?> The procedural wrapper is generally preferred: <?php Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  16. 16. Kamalakannan – 9789989552 sivkannan77@gmail.com $result = db_query("SELECT nid, title FROM {node}"); ?> Calling db_query() as above is equivalent to the following: <?php $result = Database::getConnection()->query("SELECT nid, title FROM {node}"); ?> (See why the procedural version is preferred?) db_query() takes three arguments. The first is the query string, using placeholders where appropriate and denoting all table names with curly braces. The second is an array of placeholder values. The third is, optionally, an array of configuration directives to dictate how the query will be run. Prefixing In static queries, all table names must be wrapped in {}. That flags them so that the database system can attach a prefix string to them if appropriate. Prefixing allows for running multiple sites from the same database or, in limited cases, for sharing selected tables between sites. Placeholders Placeholders mark where a literal will be inserted into a query for execution. By separating them out from the query itself, we allow the database to differentiate between SQL syntax and user- provided values, thus avoiding SQL injection. <?php $result = db_query("SELECT nid, title FROM {node} WHERE created > :created", array( ':created' => REQUEST_TIME - 3600, )); ?> The above code will select all nodes created within the past hour (3600 seconds). The placeholder :created will be dynamically replaced by whatever the value of REQUEST_TIME - 3600 is at the point the query is run. A query may have any number of placeholders, but all must have unique names even if they have the same value. Depending on the use case, the placeholders array may be specified inline (as above) or may be built beforehand and passed in. The order of the array does not matter. Placeholders beginning with "db_" are reserved for internal system use and should never be specified explicitly. Note that placeholders should not be escaped or quoted regardless of their type. Because they are passed to the database server separately, the server is able to differentiate between the query string and the value on its own. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  17. 17. Kamalakannan – 9789989552 sivkannan77@gmail.com <?php // WRONG: $result = db_query("SELECT nid, title FROM {node} WHERE type = ':type'", array( ':type' => 'page', )); // CORRECT: $result = db_query("SELECT nid, title FROM {node} WHERE type = :type", array( ':type' => 'page', )); ?> Placeholders should not (indeed, cannot) be used for column and table names. Instead, if these are derived from unsafe input, they should be run through db_escape_table(). Placeholder arrays Drupal's database layer includes an extra feature of placeholders. If the value passed in for a placeholder is an array, it will be automatically expanded into a comma separated list as will the corresponding placeholder. That means developers do not need to worry about counting how many placeholders they will need. An example should make this behavior clearer: <?php // This code: db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144)); // Will get turned into this prepared statement equivalent automatically: db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array( ':nids_1' => 13, ':nids_2' => 42, ':nids_3' => 144, )); // Which is equivalent to the following literal query: db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)"); ?> Query options The third parameter to db_query() (and to the query method of the connection object) is an array of Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  18. 18. Kamalakannan – 9789989552 sivkannan77@gmail.com options that direct how the query will behave. There are typically only two directives that will be used by most queries. The other values are mostly for internal use. The "target" key specifies the target to use. If not specified, it defaults to "default". At present, the only other valid value is "slave", to indicate that a query should run against a slave server if one exists. The "fetch" key specifies how records returned from that query will be retrieved. Legal values include PDO::FETCH_OBJ, PDO::FETCH_ASSOC, PDO::FETCH_NUM, PDO::FETCH_BOTH, or a string representing the name of a class. If a string is specified, each record will be fetched into a new object of that class. The behavior of all other values is defined by PDO, and will retrieve records as a stdClass object, an associative array, a numerical array, or an array keyed both numerically and associatively, respectively. See http://php.net/manual/en/pdostatement.fetch.php. The default is PDO::FETCH_OBJ, which for consistency should be used unless there is a specific reason to do otherwise. The following example will execute a query against a slave server if available and fetch records from the result set as an associative array. <?php $result = db_query("SELECT nid, title FROM {node}", array(), array( 'target' => 'slave', 'fetch' => PDO::FETCH_ASSOC, )); ?> Fetching into a class Queries can be fetched into objects based on custom classes. For example, if we have a class named ExampleClass the following query will return objects of the type exampleClass. <?php $result = db_query("SELECT id, title FROM {example_table}", array(), array( 'fetch' => 'ExampleClass', )); ?> If the class has a __construct() method the objects will be created, the properties will be added to the object, and then the __construct() method will be called. For example, if you have the following class and query. <?php class exampleClass { function __construct() { // Do something } } Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  19. 19. Kamalakannan – 9789989552 sivkannan77@gmail.com $result = db_query("SELECT id, title FROM {example_table}", array(), array( 'fetch' => 'ExampleClass', )); ?> The object will be created, the id and title properties will be added to the object, and then __construct() will be executed. The order of these events is due to a bug in PHP for versions less than 5.2. If there is a __construct() method on the object and that needs to be executed before the properties are added to the object the following example shows how to do this. <?php $result = db_query("SELECT id, title FROM {example_table}"); foreach ($result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'ExampleClass') as $record) { // Do something } ?> The arguments passed into fetchAll can be used in fetch the same way. PDO::FETCH_CLASS tells fetchAll to take the returned result set and add the values as properties to the object of type ExampleClass (the second argument). PDO::FETCH_PROPS_LATE tells fetchAll to add the result set as properties to the object after __construct() is called. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  20. 20. Kamalakannan – 9789989552 sivkannan77@gmail.com Dynamic queries Dynamic queries refer to queries that are built dynamically by Drupal rather than provided as an explicit query string. All Insert, Update, Delete, and Merge queries must be dynamic. Select queries may be either static or dynamic. Therefore, "dynamic query" generally refers to a dynamic Select query. All dynamically built queries are constructed using a query object, requested from the appropriate connection object. As with static queries, in the vast majority of cases the procedural wrapper may be used to request the object. Subsequent directives to the query, however, take the form of methods invoked on the query object. Table Of Contents 1. The Big Picture 2. Joins 3. Fields 4. Distinct 5. Expressions 6. Ordering 7. Random Ordering 8. Grouping 9. Ranges and Limits 10.Table Sorting 11.Conditionals 12.Executing The Query 13.Count Queries 14.Debugging Dynamic select queries are started using the db_select() function as follows: <?php $query = db_select('users', 'u', $options); ?> In this case, "user" is the base table for the query; that is, the first table after the FROM statement. Note that it should not have brackets around it. The query builder will handle that automatically. The second parameter is the alias for the table. If not specified, the name of the table is used. The $options array is optional, and is identical to the $options array for static queries. Dynamic select queries can be very simple or very complex. We will cover the basic principles of how they work here, but an exhaustive treatment would be a book unto itself. The Big Picture Here is a relatively simple query of the users table. Below we'll look at the individual parts that Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  21. 21. Kamalakannan – 9789989552 sivkannan77@gmail.com make up this query, and more advanced techniques like joins. <?php $query = db_select('users', 'u'); $query ->condition('u.uid', 0, '<>') ->fields('u', array('uid', 'name', 'status', 'created', 'access')) ->range(0, 50); $result = $query->execute(); ?> The above is roughly equivalent to $result = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0"); It is a simplified form of the query used by the user administration page, which can be referenced for further study. Joins To join against another table, use the join(), innerJoin(), leftJoin(), or rightJoin() methods, like so: <?php $query = db_select('node', 'n'); $table_alias = $query->join('users', 'u', 'n.uid = u.uid AND u.uid = :uid', array(':uid' => 5)); ?> The above directive will add an INNER JOIN (the default join type) against the "user" table, which will get an alias of "u". The join will be ON the condition " n.uid = u.uid AND u.uid = :uid", where :uid has a value of 5. Note the use of a prepared statement fragment. That allows for the addition of variable join statements in a secure fashion. Never put a literal value or variable directly into a query fragment, just as literals and variables should never be placed into a static query directly (they can lead to SQL injection vulnerabilities). The innerJoin(), leftJoin(), and rightJoin() methods operate identically for their respective join types. The return value of a join method is the alias of the table that was assigned. If an alias is specified it will be used except in the rare case that alias is already in use by a different table. In that case, the system will assign a different alias. Note that in place of a literal such as 'user' for the table name, all of the join methods will accept a select query as their first argument. Example: <?php $query = db_select('node', 'n'); Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  22. 22. Kamalakannan – 9789989552 sivkannan77@gmail.com $myselect = db_select('mytable') ->fields('mytable') ->condition('myfield', 'myvalue'); $alias = $query->join($myselect, 'myalias', 'n.nid = myalias.nid'); ?> Joins cannot be chained, so they have to be called separately (see Chaining). If you are chaining multiple functions together do it like this: <?php $query = db_select('node', 'n'); $query->join('field_data_body', 'b', 'n.nid = b.entity_id'); $query ->fields('n', array('nid', 'title')) ->condition('n.type', 'page') ->condition('n.status', '1') ->orderBy('n.created', 'DESC') ->addTag('node_access'); ?> Note: whenever querying the node table you should make use of the "node_access" tag, see also the node access rights documentation about that. Fields To add a field to the Select query, use the addField() method: <?php $title_field = $query->addField('n', 'title', 'my_title'); ?> The above code will instruct the query to select the "title" field of the table with alias "n", and give it an alias of "my_title". If no alias is specified, one will be generated automatically. In the vast majority of cases the generated alias will simply be the field name. In this example, that would be "title". If that alias already exists, the alias will be the table name and field name. In this example, that would be "n_title". If that alias already exists, a counter will be added to the alias until an unused alias is found, such as "n_title_2". Note that if you are creating and populating the query yourself and do not specify an alias and the default alias is not available, there is almost certainly a bug in your code. If you are writing a hook_query_alter() implementation, however, you cannot know with certainty what aliases are already in use so you should always use the generated alias. To select multiple fields, simply call addField() multiple times in the order desired. Note that in most cases the order of fields should not matter, and if it does then there is likely a flaw in the business logic of the module. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  23. 23. Kamalakannan – 9789989552 sivkannan77@gmail.com As an alternate shorthand, you can use the fields() method to add multiple fields at once. <?php $query->fields('n', array('nid', 'title', 'created', 'uid')); ?> The above method is equivalent to calling addField() four times, once for each field. However, fields() does not support specifying an alias for a field. It also returns the query object itself so that the method may be chained rather than returning any generated aliases. If you need to know the generated alias, either use addField() or use getFields() to access the raw internal fields structure. Calling fields() with no field list will result in a "SELECT *" query. <?php $query->fields('n'); ?> That will result in "n.*" being included in the field list of the query. Note that no aliases will be generated. If a table using SELECT * contains a field that is also specified directly from another table, it is possible for a field name collision to occur in the result set. In that case, the result set will only contain one of the fields with the common name. For that reason the SELECT * usage is discouraged. Distinct Some SQL queries may produce duplicate results. In such cases, duplicate rows may be filtered out using the "DISTINCT" keyword in a static query. In a dynamic query, use the distinct() method. <?php // Force filtering of duplicate records in the result set. $query->distinct() ?> Note that DISTINCT can introduce a performance penalty, so do not use it unless there is no other way to restrict the result set to avoid duplicates. Expressions The Select query builder supports the use of expressions in the field list. Examples of expressions include "twice the age field", "a count of all name fields", and a substring of the title field. Be aware that many expressions may use SQL functions, and not all SQL functions are standardized across all databases. It is up to the module developer to ensure that only cross-database compatible expressions are used. (Refer to this list: http://drupal.org/node/773090) To add an expression to a query, use the addExpression() method. <?php $count_alias = $query->addExpression('COUNT(uid)', 'uid_count'); $count_alias = $query->addExpression('created - :offset', 'uid_count', array(':offset' => 3600)); Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  24. 24. Kamalakannan – 9789989552 sivkannan77@gmail.com ?> The first line above will add "COUNT(uid) AS uid_count" to the query. The second parameter is the alias for the field. In the rare case that alias is already in use, a new one will be generated and the return value of addExpression() will be the alias used. If no alias is specified, a default of "expression" (or expression_2, expression_3, etc.) will be generated. The optional third parameter is an associative array of placeholder values to use as part of the expression. Note that some expressions may not function unless accompanied by a Group By clause. It is up to the developer to ensure that the query that is generated is in fact valid. Ordering To add an order by clause to a dynamic query, use the orderBy() method: <?php $query->orderBy('title', 'DESC'); ?> The above code will instruct the query to sort by the title field in descending order. The second parameter may be either "ASC" or "DESC" for ascending or descending, respectively, and defaults to "ASC". Note that the field name here should be the alias created by the addField() or addExpression() methods, so in most cases you will want to use the return value from those methods here to ensure the correct alias is used. To order by multiple fields, simply call orderBy() multiple times in the order desired. Random ordering Random ordering of queries requires slightly different syntax on different databases. Therefore, that is best handled by a dynamic query. To indicate that a given query should order randomly, call the orderRandom() method on it. <?php $query->orderRandom(); ?> Note that orderRandom() is chainable, and stackable with orderBy(). That is, it is safe to do something like the following: <?php $query->orderBy('term')->orderRandom()->execute(); ?> The above would order first by the "term" field of the query and then, for records that have the same term, order randomly. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  25. 25. Kamalakannan – 9789989552 sivkannan77@gmail.com Grouping To group by a given field, use the groupBy() method. <?php $query->groupBy('uid'); ?> The above code will instruct the query to group by the uid field. Note that the field name here should be the alias created by the addField() or addExpression() methods, so in most cases you will want to use the return value from those methods here to ensure the correct alias is used. To group by multiple fields, simply call groupBy() multiple times in the order desired. Ranges and Limits Queries may also be restricted to a certain subset of the records found. In general this is known as a "range query". In MySQL, this is implemented using the LIMIT clause. To limit the range of a query, use the range() method: <?php $query->range(5, 10); ?> The above code will instruct the result set to start at the 6th record found (the count starts at 0) rather than the first, and to return only 10 records. In most cases one will want "the first n records". To do that, pass 0 as the first argument and n as the second. Calling the range() method a second time will overwrite previous values. Calling it with no parameters will remove all range restrictions on the query. Table sorting To produce a result table which can be sorted by any column, use the TableSort extender and then add the table header. Note that an extender does return a new query object that you need to use from that point on. <?php $query = $query ->extend('TableSort') ->orderByHeader($header); ?> Conditionals Conditionals are a complex subject and are shared by Select, Update, and Delete queries. They are therefore explained separately. Unlike Update and Delete queries, however, Select queries have two types of conditionals: The WHERE clause and the HAVING clause. The Having clause behaves identically to the WHERE clause, except that it uses methods havingCondition() and having() Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  26. 26. Kamalakannan – 9789989552 sivkannan77@gmail.com instead of condition() and where(). Executing the query Once the query is built, call the execute() method to compile and run the query. <?php $result = $query->execute(); ?> The execute() method will return a result set / statement object that is identical to that returned by db_query(), and it may be iterated or fetched in the exact same way: <?php $result = $query->execute(); foreach ($result as $record) { // Do something with each $record } ?> Note: Be careful when using the following methods with a multi-column, dynamic query: • fetchField() • fetchAllKeyed() • fetchCol() These methods currently require numeric column indicies (0, 1, 2, etc.) rather than table aliases. However, the query builder does not currently guarantee any specific order for the returned fields, so the data columns may not be in the order that you expect. In particular, expressions are always added after fields, even if you add them to your query first. (This issue does not apply to static queries, which always return the data columns in the order you specify.) Count queries Any query may have a corresponding "count query". The count query returns the number of rows in the original query. To obtain a count query, use the countQuery() method. <?php $count_query = $query->countQuery(); ?> $count_query is now a new Dynamic Select query with no ordering restrictions that when executed will return a result set with only one value, the number of records that would be matched by the original query. Because PHP supports chaining methods on returned objects, the following idiom is a common approach: <?php $num_rows = $query->countQuery()->execute()->fetchField(); ?> Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  27. 27. Kamalakannan – 9789989552 sivkannan77@gmail.com Debugging To examine the SQL query that the query object will build at a particular point in its lifecycle, call its __toString() method: <?php print_r($query->__toString()); ?> Extenders Select queries support the concept of "extenders". An extender is a way to add functionality to a Select query at runtime. That functionality could be additional methods or altering the behavior of existing methods. For those familiar with object-oriented design patterns, extenders are an implementation of the Decorator Pattern. They attach additional responsibilities to an object dynamically by providing a flexible alternative to subclassing for extending functionality. Using an Extender To use an extender, you must first have a query object. From the query object, the extend() method will return a new object that should be used in place of the query object. For example: <?php $query = $query->extend('PagerDefault'); ?> The above line takes a select query, creates a new PagerDefault query object that contains the original select query, and returns the new object. $query may now be used as if it were the original query object but with additional methods now available. Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost. For example, the following will not do what you expect: <?php $query = db_select('node', 'n'); $query ->fields('n', array('nid', 'title') ->extend('PagerDefault') // This line returns a new PagerDefault object. ->limit(5); // This line works, because the PagerDefault object is what is called. // The return from extend() was never saved to a variable, so $query is still just the Select object. $query->orderBy('title'); Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  28. 28. Kamalakannan – 9789989552 sivkannan77@gmail.com // This line executes the Select object, not the extender. The extender no longer exists. $result = $query->execute(); ?> To avoid this problem, the recommended convention for extending a Select query is to do so when the query is first declared. <?php $query = db_select('node', 'n')->extend('PagerDefault')- >extend('TableSort'); $query->fields(...); // ... ?> That ensures that $query is the fully extended object right from the beginning. Also note that while extenders may be stacked (as in the example above), not all extenders are compatible with other extenders and the order may matter. For example, a query that is extended with both a pager and table-sort behavior must be extended with PagerDefault first. Creating new extenders An extender is simply a class that implements the SelectQueryInterface, and takes two parameters in its constructor: A select query (or rather, another object that implements SelectQueryInterface) and a DatabaseConnection object. It must then re-implement the methods of SelectQueryInterface and pass them through to query object specified in the constructor, returning itself where appropriate. In the vast majority of cases, all of that can be done by extending the SelectQueryExtender class which handles all of that internally. In practice, therefore, an extender is any class that extends SelectQueryExtender. The name of the class is what should be specified in the extend() call from a query object. It is up to the extender class, then, to add or override methods as appropriate. Any method that it does not override will be transparently passed through to the wrapped query object. When overriding a method, the extender may or may not call the underlying query object but it must return the same value that is expected from the SelectQuery interface. In most cases, that is the query object itself, or for the extender the extender object itself. The following example should make that clearer. <?php class ExampleExtender extends SelectQueryExtender { /** * Override the normal orderBy behavior. */ public function orderBy($field, $direction = 'ASC') { Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  29. 29. Kamalakannan – 9789989552 sivkannan77@gmail.com return $this; } /** * Add a new method of our own. */ public function orderByForReal($field, $direction = 'ASC') { $this->query->orderBy($field, $direction); return $this; } } ?> The example above overrides the orderBy() method of a query to do nothing, but adds another method, orderByForReal(), that implements actual ordering behavior. (Naturally this is a rather pointless example, but it does serve to illustrate how extenders work.) Note that in both methods, the $this being returned is the extender object itself. That ensures that the extender doesn't "get lost" by returning the query object. Any module may declare an Extender. Core ships with two that are generally useful: PagerDefault and TableSort. See the API documentation for those classes for how to leverage them in your own code. Supporting multiple database types The extend method works the same way as db_select, in that it searches for a class name that is suffixed with the database driver. Therefore, you can define a class ExampleExtender_pgsql as well as ExampleExtender and the former will be used if applicable. Query alteration An important feature of dynamic select queries is the ability of other modules to alter them on the fly. That allows other modules to inject their own restrictions into the query, either to alter a module's behavior or to apply runtime restrictions on the query, such as node access restrictions. There are three components to query alteration: tagging, meta data, and hook_query_alter(). Only queries that have been tagged by the original creator can be altered later. Most of Drupals everyday small queries are not explicitly tagged and therefore not alterable in this way. Tagging Any dynamic Select query may be "tagged" with one or more strings. These tags serve to identify the type of query it is, which in turn allows alter hooks to determine if they need to take action. Tags Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  30. 30. Kamalakannan – 9789989552 sivkannan77@gmail.com should be an alphanumeric lowercase string, following the same rules as a PHP variable. (That is, letters, numbers, and underscores only and must begin with a letter.) To add a tag to a query, use the addTag() method: <?php $query->addTag('node_access'); ?> To determine if a given query object has been tagged with a given tag, there are three methods available: <?php // TRUE if this query object has this tag. $query->hasTag('example'); // TRUE if this query object has every single one of the specified tags. $query->hasAllTags('example1', 'example2'); // TRUE if this query object has at least one of the specified tags. $query->hasAnyTag('example1', 'example2'); ?> Both hasAllTags() and hasAnyTag() take an arbitrary number of parameters with each tag as its own parameter. Order does not matter. There is no hard restriction on what tags may be used, but certain standard tags are commonly used. A partial list of standardized tags is listed below: node_access This query should have node access restrictions placed on it; all queries that retrieve a list of nodes (or node IDs) for display to users should have this tag. However, note that when the Node module alters queries with this tag, it does not check the published/unpublished status of nodes, so your base query is responsible for ensuring that unpublished nodes are not displayed to inappropriate users. entity_field_access This query should have entity field access restrictions placed on it. translatable This query should have translatable columns. term_access This query should have taxonomy term-based restrictions placed on it; all queries that retrieve a list of taxonomy terms for display to users should ahve this tag. views This query is generated by the views module. Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  31. 31. Kamalakannan – 9789989552 sivkannan77@gmail.com Meta data Queries may also have meta data attached to them to provide additional context to alter hooks. Meta data may be any PHP variable, and is keyed by a string. <?php $node = node_load($nid); // ... Create a $query object here. $query->addMetaData('node', $node); ?> Meta data has no intrinsic meaning, and on its own has no effect on the query object. It exists only to provide additional information to alter hooks, and generally only apply when the query has certain tags. To access a given piece of meta data on a query, use the getMetaData() method. <?php $node = $query->getMetaData('node'); ?> If no meta data has been assigned with that key, NULL will be returned. hook_query_alter() Neither tagging nor meta data do anything on their own. Both exist solely to provide information to hook_query_alter(), which can take virtually any action on a Select query. All Dynamic Select query objects are passed through hook_query_alter() by the execute() method, immediately before the query string is compiled. That gives modules the opportunity to manipulate the query as desired. hook_query_alter() accepts a single parameter: the Select query object itself. <?php /** * Implementation of hook_query_alter(). */ function example_query_alter(QueryAlterableInterface $query) { // ... } ?> There is also a tag-specific alter hook, hook_query_TAG_NAME_alter(), that is called for every tag on a given Select query, after the generic one has been called. The following example is called for queries that have the tag 'node_access': <?php function example_query_node_access_alter(QueryAlterableInterface $query) { Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  32. 32. Kamalakannan – 9789989552 sivkannan77@gmail.com // ... } ?> There are two important observations to be made regarding hook_query_alter(). 1. The $query parameter is not passed by reference. Because it is an object, the object will not be duplicated anyway due to the way PHP 5 and later handles objects. Passing by reference is therefore unnecessary. The alter hook also has no return value. 2. The parameter type is explicitly specified as QueryAlterableInterface. While not strictly necessary, explicitly specifying the parameter type provides slightly better runtime protection against passing in the wrong type of variable. The type is also specified as QueryAlterableInterface rather than simply SelectQuery to better provide forward compatibility. The alter hook may take any action on the query object it wishes, except executing the query again as that would result in an infinite loop. The alter hook may make use of the tags and meta data associated with a query to determine what if any action to take. Module developers may either call additional methods on the query object as listed above to add additional fields, joins, conditionals, etc. to the query, or may request access to the query object's internal data structures to manipulate them directly. The former is preferred for adding new information to a query while the latter allows the alter hook to remove information from a query or manipulate instructions already queued up. <?php $fields =& $query->getFields(); $expressions =& $query->getExpressions(); $tables =& $query->getTables(); $order =& $query->getOrderBy(); $where =& $query->conditions(); $having =& $query->havingConditions(); ?> It is important to note that all of the above must be returned by reference (=&) so that the alter hook is accessing the same data structure as the object. All of the above methods return an array, the general structure of which is documented in the inline documentation of SelectQuery in includes/database/select.inc. Result sets A Select query will always return a result set object of zero or more records. There are several ways to then retrieve data from that result set, depending on the use case. The most common case is to iterate over the result set with a foreach() loop. <?php $result = db_query("SELECT nid, title FROM {node}"); foreach ($result as $record) { // Do something with each $record Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.
  33. 33. Kamalakannan – 9789989552 sivkannan77@gmail.com $node = node_load($record->nid); } ?> Depending on what the results are needed for, however, there are a number of other ways to retrieve the records. To explicitly fetch the next record, use: <?php $record = $result->fetch(); // Use the default fetch mode. $record = $result->fetchObject(); // Fetch as a stdClass object. $record = $result->fetchAssoc(); // Fetch as an associative array. ?> If there is no next record, FALSE will be returned. fetch() should generally be avoided in favor of fetchObject() and fetchAssoc(), as the latter are more self-documenting. If you need to use some other PDO-supported fetch mode, then use fetch(). To fetch just a single field out of the result set, use: <?php $record = $result->fetchField($column_index); ?> The default value of $column_index is 0, for the first field. To count the number of Rows returned use: <?php $number_of_rows = $result->rowCount(); ?> To fetch all records at once into a single array, use one of the following: <?php // Retrieve all records into an indexed array of stdClass objects. $result->fetchAll(); // Retrieve all records into an associative array keyed by the field in the result specified. $result->fetchAllAssoc($field); // Retrieve a 2-column result set as an associative array of field 1 => field 2. $result->fetchAllKeyed(); // You can also specify which two fields to use by specifying the column numbers for each field $result->fetchAllKeyed(0,2); // would be field 0 => field 2 Drupal’s online documentation is © 2000-2012 by the individual contributors. content collected from Drupal.org Drupal is a registered trademark of Dries Buytaert.

×