Drupal 7 API Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4
At a glance
Powered by AI
The document discusses the different methods available for constructing database queries in Drupal, including selecting fields, filtering results, joining tables, sorting, and working with query results.

The document discusses that inner, left, and right joins can be used in a database query. Inner joins return rows where there is a match in both tables, left joins return all rows from the left table even if there is no match, and right joins return all rows from the right table.

The document states that results can be ordered by fields in ascending or descending order using the orderBy method. Additional methods like orderRandom can randomize the results ordering.

SELECT db_select($table, $alias = NULL, $options = array()) $table! $alias ! return! Database table to select from. Table alias.

New query object.

->orderRandom() return! The called query object.

->db_or()->condition()->condition() return! Condition of OR-ed conditions.

->union(SelectQueryInterface $query, $type = '') $query ! $type! return! Query to union. Type of union. New resulting query object.

->db_and()->condition()->condition() return ! Condition of AND-ed conditions.

->isNull($field) ->isNotNull($field) $eld! return! The eld to check. The called query object.

$query = db_select('users', 'u') ->fields('u', array('uid', 'name')); $result = $query->execute(); ->distinct($distinct = TRUE) $distinct! return! Flag indicating DISTINCT query. The called query object.

->addExpression($expression, $alias = NULL, $arguments = array()) $expression! $alias ! $arguments! return! Expression string. Expression alias. Assoc array of placehoders and placeholder values. Unique expression alias.

->exists(SelectQueryInterface $select); ->notExists(SelectQueryInterface $select); $select! return! The query to check. The called query object. JOIN PAGER ->extend(PagerDefault) return! New pager extender object.

->fields($table_alias, $fields = array()) $table_alias! $elds! return! Alias of the table the eld belongs to. Array of eld names. The called query object.

->countQuery() return! New query object.

->addTag($tag) $tag! return! Query identication. The called query object. ->join($table, $alias = NULL, $condition = NULL, $arguments = array()) $table! $alias ! $condition! $arguments! return! The table to join with. Table alias. Join conditions. Assoc array of placeholders and placeholder values. Unique table alias.

->addField($table_alias, $field, $alias = NULL) $table_alias! $eld! $alias ! return! Alias of the table the eld belongs to. Field name. Field alias. Unique eld alias.

->hasTag($tag) $tag! return! Query identication. TRUE if condition is met. CONDITIONS ->condition($field, $value = NULL, $operator = NULL) $eld! $value! $operator" ! The eld to check or the result of a logic operation (or, and, xor) The value to test against. Default: = or IN. Supported: =, <, >, >=, <=, IN, NOT IN, LIKE, BETWEEN, IS NULL, IS NOT NULL The called query object.

->extend(PagerDefault)->limit ($count) $count! Number of items per page. SORTABLE TABLE ->extend(TableSort) return! return! Table extender object. The called query object.

->range($start = NULL, $length = NULL) $start! $length! return! First record of the result set. Max number of records. The called query object.

$query = db_select('users', 'u'); $query->innerJoin('node', 'n', 'n.uid = u.uid'); $query->addField('u', 'name'); $query->addField('n', 'title'); $result = $query->execute(); ->innerJoin ($table, $alias = NULL, $condition = NULL, $arguments = array()) ->leftJoin ($table, $alias = NULL, $condition = NULL, $arguments = array()) ->rightJoin ($table, $alias = NULL, $condition = NULL, $arguments = array()) See join method.

->extend(TableSort)->orderByHeader ($header) $header! return! Array with sorting criteria. The called query object.

->groupBy($field) $eld! return! The eld to group by. The called query object. return!

->orderBy($field, $direction = 'ASC') $eld! $direction! return! The eld to order by. 'ASC' or 'DESC'. The called query object.

->where($snippet, $args = array()) $snippet! $args! Where clause (with placeholders) Assoc array of placeholders and placeholder values.

$header = array( array( 'data' => t('Title'), 'field' => 'n.title', 'sort' => 'desc'), t('Operations'), );

March 2011!

Drupal-7 database !

www.wizzlern.nl/drupal/cheat-sheets

RESULTS ->execute($args = array(), $options = array()) return! The called query object.

->fetchCol($index = 0) $index! return! Numeric index of the column. Array of all records. INSERT db_insert($table, $options = array ()) $table! return! Database table to insert into. New query object.

->fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL) $mode! return! Fetch mode. Result type specied by $mode.

$num_updated = db_update('node') ! ->fields(array( !!! 'uid' => 5, !!! 'status' => 1, ! )) ! ->condition('created', REQUEST_TIME - 3600, '>=') ! ->execute(); MERGE db_merge($table, $options = array()) $table! return! Database table to merge into New query object

->fetchObject($class_name = NULL, $constructor_args = array()) $class_name! return! Class type to be returned. Default: stdClass Object of one record.

$nid = db_insert('node') ! ->fields(array( !!! 'title' => 'Example', !!! 'uid' => 1, !!! 'created' => REQUEST_TIME)) ! ->execute(); ->values(array $values)

->fetchAssoc() return! Associative array of one record.

$values! return!

Assoc array of values to insert. The called query object.

db_merge('role') ! ->key(array('name' => $name)) ! ->fields(array( !!!!! 'weight' => $weight, ! )) ! ->execute(); ->key(array $fields, $values = array ()) $elds! Array of elds to match or set. Or associative array of elds and values. Values to set. The called query object. DELETE

QUERIES db_query($query, $args = array(), $options = array()) Note: Access control is not supported! Query may not be compatible with other database types. settings.php Single database conguration example: $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'databasename', 'username' => 'username', 'password' => 'password', 'host' => 'localhost', 'prefix' => '', 'collation' =>'utf8_general_ci', ); DEBUGGING

->fetchAllAssoc($key, $fetch = NULL) $key! $fetch! Field name of the array key Fetch mode (PDO::FETCH_ASSOC, PDO::FETCH_NUM, or PDO::FETCH_BOTH). Associative array of data objects

return !

$nid = db_insert('node') ! ->fields(array('title', 'uid', 'created')) ! ->values(array( !!! 'title' => 'Example', !!! 'uid' => 1, !!! 'created' => REQUEST_TIME)) ! ->execute(); ->from(SelectQueryInterface $query) $query ! return! Select query to fetch the rows that should be inserted. The called query object. UPDATE

$values! return!

->fetchAll($mode = NULL, $column_index = NULL, $constructor_arguments = array()) $mode! return! Fetch mode. See above. Array of data objects. Depending on fetch mode.

db_delete($table, $options = array ()) $table! return! Database table to delete from. New query object.

->fetchField($index = 0) $index! return! Numeric index of the column. A single eld.

db_update($table, $options = array ()) $table! return! Database table to update. New query object.

$num_deleted = db_delete('node') ! ->condition('nid', 5) ! ->execute(); TRUNCATE

->fetchAllKeyed($key_index = 0, $value_index = 1) $key_index! $value_index ! return! Numeric index of the array key. Numeric index of the array value. Associative array of all records.

print($query->__toString()); db_truncate($table, $options = array ()) $table! return! Database table to remove. New query object. DOCUMENTATION Database API on drupal.org: http://drupal.org/developing/api/database

March 2011!

Drupal-7 database !

www.wizzlern.nl/drupal/cheat-sheets

JQUERY Compatibility code (function ($) { ! // ... Your code here ... }(jQuery)); Execute code when DOM is loaded $(function() { ! // ... Your code here ... }); Drupal.settings <?php drupal_add_js(array( 'my_module' => array('color' => 'green')), 'setting' ); ?> $('#id') .css({'color': Drupal.settings.my_module.color}); Drupal.behaviors Drupal.behaviors.mybehavior = { attach: function (context, settings) { $('#id', context) .once('mybehavior', function () { // ... Your code here ... }); } }; Drupal.checkPlain(str) str! return ! String to be sanitised. Sanitised string

PHP drupal_add_js($data = NULL, $options = NULL) $data! le! inline! external! setting! $options! type! scope! group! every_page! weight! defer! cache! preprocess ! Depending on option 'type': Relative path to le Javascript code Absolute path to le Array of settings Type or array of options: le, inline, external, setting header, footer Group: JS_LIBRARY, JS_DEFAULT, JS_THEME TRUE = Load on all pages. Sort order <script> defer attribute. TRUE = Cache this Javascript. JS aggregation enabled.

Drupal.formatPlural(count, singular, plural, args) count! Number to be included in string. singular! Singular string plural! Plural string args ! Replacement arguments. See Drupal.t() return! Translated string. Drupal.formatPlural(count, 'One string', '@count strings'); Drupal.theme.prototype Drupal.theme.prototype.placeholder = function (str) { return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>'; }; Drupal.theme(func, args) func! Theme function. args ! Arguments for theme function. return! HTML output. Drupal.theme('placeholder', 'Hello!'); Drupal.attachBehaviors(context, settings) context! settings ! Context for the attach() method. Default: 'document' Settings for the attach() method. Default: Drupal.settings

drupal_add_js('misc/collapse.js'); drupal_add_js(array('myModule' => array ('my_setting' => 'my value')), 'setting'); drupal_add_js( 'jQuery(document).ready( function () { alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5, ), ); drupal_add_js('http://example.com/example.js', 'external'); hook_js_alter(&$javascript) $javascript! Array of JavaScript (les) to be added to the page.

Drupal.t(str, args) str! String to be translated. args ! Replacement arguments. !arg! Unchanged @arg! Sanitized %arg! Sanitized + em tag return! Translated string. Drupal.t('@lang string', {'@lang': language});

August 2011!

Drupal 7 jQuery !

www.wizzlern.nl/drupal/cheat-sheets

STATES #states <state>! State to be applied when conditions are met. See drupal_process_states(). For all form element types: enabled, disabled, required. optional, visible, invisible, checked, unchecked, expanded, collapsed. For some form element types: relevant, irrelevant, valid, invalid, touched, untouched, readwrite, readonly. '#states' => array( // Show the form element if 'bar' has been selected for 'foo'. 'visible' => array( ':input[name="foo"]' => array('value' => 'bar'), ), ), AJAX #ajax callback! effect! event! keypress! method! path! prevent! progress! trigger_as ! wrapper! Callback function which can return HTML, renderable array, or array of AJAX Commands. Effect used when adding content none, fade, slide Event at which the HTTP request occurs. Optional. TRUE: Event is triggered when Enter key is pressed. Manipulation method of the 'wrapper' content. replace, after, append, before, prepend. Callback path. Default: system/ajax Event(s) that should not trigger the ajax call. Progress bar settings: 'type', 'message', 'url', 'interval'. Form element to handle the event trigger. Id attribute of DOM element to be replaced by callback. (no '#')

'#weight' => 1, '#submit' => array('poll_more_choices_submit'), '#ajax' => array( 'callback' => 'poll_choice_js', 'wrapper' => 'poll-choices', 'method' => 'replace', 'effect' => 'fade', ), ); ... } function poll_choice_js($form, $form_state) { return $form['choice_wrapper']['choice']; } jQuery.ajax() $.ajax({ url: Drupal.settings.basePath + 'jquery_demo/ajax/' + string, success: function(data) { alert(data.message); } error: function (xmlhttp) { alert(Drupal.ajaxError(xmlhttp, db.uri)); } }); DRUPAL JS LIBRARIES drupal_add_library($module, $name, $every_page = NULL) $module! $name! $every_page! return! Module that registered a library. Library name. TRUE: add to every page. TRUE on succes. jQuery UI Effects libraries: effects, effects.blind, effects.bounce, effects.clip, effects.drop, effects.explode, effects.fade, effects.fold, effects.highlight, effects.pulsate, effects.scale, effects.shake, effects.slide, effects.transfer. Other libraries: once, form, jquery-bbq, vertical-tabs, cookie. hook_library() $libraries['ui.tabs'] = array( 'title' => 'jQuery UI: Tabs', 'website' => 'http://jqueryui.com/demos/tabs/', 'version' => '1.8.7', 'js' => array( 'misc/ui/jquery.ui.tabs.min.js' => array(), ), 'css' => array( 'misc/ui/jquery.ui.tabs.css' => array(), ), 'dependencies' => array( array('system', 'ui.widget'), ), ); DOCUMENTATION jQuery UI libraries: ui, ui.accordion, ui.autocomplete, ui.button, ui.datepicker, ui.dialog, ui.draggable, ui.droppable, ui.mouse, ui.position, ui.progressbar, ui.resizable, ui.selectable, ui.slider, ui.sortable, ui.tabs, ui.widget. jQuery: jquery.com, visualjquery.com, jqueryui.com Drupal jQuery: Javascript startup guide

Drupal system libraries: drupal.ajax, drupal.batch, drupal.progress, drupal.form, drupal.states, drupal.collapse, drupal.textarea, drupal.autocomplete. jQuery libraries: jquery, jquery.once, jquery.form, jquery.bbq, drupal.vertical-tabs, farbtastic, jquery.cookie.

function poll_form(&$node, $form_state) { ... $form['choice_wrapper']['poll_more'] = array( '#type' => 'submit', '#value' => t('More choices'), '#description' => t("Add more choices."),

August 2011!

Drupal 7 jQuery !

www.wizzlern.nl/drupal/cheat-sheets

You might also like