Appendix C. Selected Reference Material

This appendix is for all the things I promised in the rest of the book. It is a helper for commonly used reference materials, such as Drupal's API section, http://api.drupal.org—the best place to learn about the functions and classes available in Drupal. Remember, the Drupal core is always evolving and the calls might change from version to version. The Drupal API site will also show you the most recent version of all interfaces.

Core Template Variables

In Chapter 7, I talked about using Drupal's theme template engine to get control over the look of various parts of the content created by the Drupal database engine. The Drupal core ships with a number of templates. Each of these templates makes available certain variables, depending on the template.

Each of the variables ($styles, $site_name, $content, $search_box, etc.) must be generated in a module and made available as global variables so the Drupal's page-creation logic can render them. Table C-1 provides a list of variables for each template that ships with the Drupal 7 core.

Table C.1. Drupal 7 Core Templates

Template

Available Variables

 

block.tpl.php

$block->subject

Block title.

 

$content

Block content.

Default theme implementation to display a block.

$block->module

Module that generated the block.

 

$block->delta

An ID for the block, unique within each module.

 

$block->region

The block region embedding the current block.

 

$classes

String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:

block

The current template type, i.e., the "theming hook."

block-[module]

The module generating the block. For example, the user module is responsible for handling the default user navigation block. In that case, the class would be "block-user."

 

$title_prefix

An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.

 

$title_suffix

An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

 

$classes_array

Array of HTML class attribute values. It is flattened into a string within the variable $classes.

 

$block_zebra

Outputs 'odd' and 'even' dependent on each block region.

 

$zebra

Same output as $block_zebra but independent of any block region.

 

$block_id

Counter dependent on each block region.

 

$id

Same output as $block_id but independent of any block region.

 

$is_front

Flags true when presented in the front page.

 

$logged_in

Flags true when the current user is a logged-in member.

 

$is_admin

Flags true when the current user is an administrator.

 

$block_html_id

A valid HTML ID and guaranteed unique.

comment-wrapper.tpl.php

$content

The array of content-related elements for the node. Use render($content) to print them all, or print a subset such as render($content['comment_form']).

Default theme implementation to provide an HTML container for comments.

$classes

String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default value has the following: comment-wrapper: The current template type, i.e., the "theming hook."

 

$title_prefix

An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.

 

$title_suffix

An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

 

$node

Node object the comments are attached to.

 

$classes_array

Array of HTML class attribute values. It is flattened into a string within the variable $classes.

comment.tpl.php

Default theme implementation for comments.

$author

$content

Comment author. Can be a link or plain text.

An array of comment items. Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.

Formatted date and time when the comment was created. Preprocess functions can reformat it by calling format_date() with the desired parameters on the $comment->created variable.

 

$changed

Formatted date and time when the comment was last changed. Preprocess functions can reformat it by calling format_date() with the desired parameters on the $comment->changed variable.

 

$new

New comment marker.

 

$permalink

Comment permalink.

 

$picture

The author's picture.

 

$created

The author's signature.

 

$status

Comment status. Possible values are: comment-unpublished comment-published, comment-preview.

 

$title

Linked title.

 

$classes

String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:

comment

The current template type, i.e., the "theming hook."

comment-by-anonymous

Comment by an unregistered user.

comment-by-node-author

Comment by the author of the parent node.

comment-preview

Preview of a new or edited comment.

comment-unpublished

An unpublished comment visible only to administrators.

comment-by-viewer

Comment by the user currently viewing the page.

comment-new

New comment since last the visit.

 

$title_prefix

An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.

 

$title_suffix

An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

 

$comment

Full comment object.

 

$node

Node object the comments are attached to.

 

$classes_array

Array of HTML class attribute values. It is flattened into a string within the variable $classes.

field.tpl.php

Default template implementation to display the value of a field. This file is not used and is here as a starting point for customization only.

  • $items: An array of field values. Use render() to output them.

  • $label: The item label.

  • $label_hidden: Whether the label display is set to 'hidden'.

  • $classes: String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:

    • field: The current template type, i.e., the "theming hook."

    • field-name-[field_name]: The current field name. For example, if the field name is "field_description," the result would be "field-name-field-description."

    • field-type-[field_type]: The current field type. For example, if the field type is "text," the result would be "field-type-text."

    • field-label-[label_display]: The current label position. For example, if the label position is "above," the result would be "field-label-above."

Other variables:

  • $element['#object']: The entity to which the field is attached.

  • $element['#view_mode']: View mode, e.g., 'full', 'teaser'...

  • $element['#field_name']: The field name.

  • $element['#field_type']: The field type.

  • $element['#field_language']: The field language.

  • $element['#field_translatable']: Whether the field is translatable or not.

  • $element['#label_display']: Position of label display, inline, above, or hidden.

  • $field_name_css: The css-compatible field name.

  • $field_type_css: The css-compatible field type.

  • $classes_array: Array of HTML class attribute values. It is flattened into a string within the variable $classes.

html.tpl.php

Default theme implementation to display the basic HTML structure of a single Drupal page.

  • $css: An array of CSS files for the current page.

  • $language: (object) The language the site is being displayed in.

  • $language->language: Contains its textual representation.

  • $language->dir: Contains the language direction, either be 'ltr' or 'rtl'.

  • $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.

  • $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.

  • $head_title: A modified version of the page title, for use in the TITLE tag.

  • $head: Markup for the HEAD section (including meta tags, keyword tags, and so on).

  • $styles: Style tags for importing all CSS files for the page.

  • $scripts: Script tags for loading the JavaScript files and settings for the page.

  • $page_top: Initial markup from any modules that have altered the page. This variable should always be output first, before all other dynamic content.

  • $page: The rendered page content.

  • $page_bottom: Final closing markup from any modules that have altered the page. This variable should always be output last, after all other dynamic content.$classes: String of classes that can be used to style contextually through CSS.

node.tpl.php

Default theme implementation to display a node

  • $title: the (sanitized) title of the node.

  • $content: An array of node items. Use render($content) to print them all, or print a subset such as render($content['field_example']). Use hide($content['field_example']) to temporarily suppress the printing of a given element.

  • $user_picture: The node author's picture from user-picture.tpl.php.

  • $date: Formatted creation date. Preprocess functions can reformat it by calling format_date() with the desired parameters on the $created variable.

  • $name: Themed username of node author output from theme_username().

  • $node_url: Direct URL of the current node.

  • $display_submitted: whether submission information should be displayed.

  • $classes: String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:

    • node: The current template type, i.e., the "theming hook."

    • node-[type]: The current node type. For example, if the node is a "Blog entry" the result would be "node-blog." Note that the machine name will often be in a short form of the human readable label.

    • node-teaser: Nodes in teaser form.

    • node-preview: Nodes in preview mode.

    • node-promoted: Nodes promoted to the front page.

    • node-sticky: Nodes ordered above other non-sticky nodes in teaser listings.

    • node-unpublished: Unpublished nodes visible only to administrators.

  • $title_prefix: An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.

  • $title_suffix: An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

Other variables:

  • $node: Full node object. Contains data that may not be safe.

  • $type: Node type, i.e., story, page, blog, etc.

  • $comment_count: Number of comments attached to the node.

  • $uid: User ID of the node author.

  • $created: Time the node was published, formatted in Unix timestamp.

  • $classes_array: Array of html class attribute values. It is flattened into a string within the variable $classes.

  • $zebra: Outputs either "even" or "odd." Useful for zebra striping in teaser listings.

  • $id: Position of the node. Increments each time its output.

Node status variables:

  • $view_mode: View mode, e.g., 'full', 'teaser'...

  • $teaser: Flag for the teaser state (shortcut for $view_mode == 'teaser').

  • $page: Flag for the full page state.

  • $promote: Flag for front page promotion state.

  • $sticky: Flags for sticky post setting.

  • $status: Flag for published status.

  • $comment: State of comment settings for the node.

  • $readmore: Flags true if the teaser content of the node can't hold the main body content.

  • $is_front: Flags true when presented on the front page.

  • $logged_in: Flags true when the current user is a logged-in member.

  • $is_admin: Flags true when the current user is an administrator.

Field variables: for each field instance attached to the node a corresponding variable is defined, e.g., $node->body becomes $body. When it's necessary to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise, you'll have to explicitly specify the desired field language, such as $node->body['en'], thus overriding any language negotiation rule that was previously applied.

page.tpl.php

Default theme implementation to display a single Drupal page.

  • $base_path: The base URL path of the Drupal installation. At the very least, this will always default to /.

  • $directory: The directory the template is located in, such as modules/system or themes/garland.

  • $is_front: TRUE if the current page is the front page.

  • $logged_in: TRUE if the user is registered and signed in.

  • $is_admin: TRUE if the user has permission to access administration pages.

Site identity:

  • $front_page: The URL of the front page. Use this instead of $base_path, when linking to the front page. It includes the language domain or prefix.

  • $logo: The path to the logo image, as defined in theme configuration.

  • $site_name: The name of the site, empty when display has been disabled in theme settings.

  • $site_slogan: The slogan of the site, empty when display has been disabled in theme settings.

Navigation:

  • $main_menu: An array containing the Main menu links for the site, if they have been configured.

  • $secondary_menu: An array containing the Secondary menu links for the site, if they have been configured.

  • $breadcrumb: The breadcrumb trail for the current page.

Page content (in order of occurrence in the default page.tpl.php):

  • $title_prefix: An array containing additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.

  • $title: The page title, for use in the actual HTML content.

  • $title_suffix: An array containing additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

  • $messages: HTML for status and error messages. Should be displayed prominently.

  • $tabs: Tabs linking to any sub-pages beneath the current page (e.g., the view and edit tabs when displaying a node).

  • $action_links: Actions local to the page, such as 'Add menu' on the menu administration interface.

  • $feed_icons: A string of all feed icons for the current page.

  • $node: The node object, if there is an automatically-loaded node associated with the page; the node ID is the second argument in the page's path (e.g., node/12345 and node/12345/revisions, but not comment/reply/12345).

Regions:

  • $page['help']: Dynamic help text, mostly for admin pages.

  • $page['highlight']: Items for the highlighted content region.

  • $page['content']: The main content of the current page.

  • $page['sidebar_first']: Items for the first sidebar.

  • $page['sidebar_second']: Items for the second sidebar.

  • $page['header']: Items for the header region.

  • $page['footer']: Items for the footer region.

region.tpl.php

Default theme implementation to display a region.

  • $content: The content for this region, typically blocks.

  • $classes: String of classes that can be used to style contextually through CSS. The string can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:

    • region: The current template type i.e., the "theming hook."

    • region-[name]: The name of the region with underscores replaced by dashes. For example, the page_top region would have a region-page-top class.

    • $region: The name of the region variable as defined in the theme's .info file.

Helper variables:

  • $classes_array: Array of HTML class attribute values. It is flattened into a string within the variable $classes.

  • $is_admin: Flags true when the current user is an administrator.

  • $is_front: Flags true when presented on the front page.

  • $logged_in: Flags true when the current user is a logged-in member.

SimpleTest Reference

SimpleTest is the testing framework that is built into Drupal 7. Table C-2 shows some binary assertions. Table C-3 lists content assertions. Table C-4 shows SimpleTest navigation functions. Table C-5 shows request modifiers.

Table C.2. SimpleTest Binary Assertions

Assertion

Description

assertTrue($x)

Fail if $x is false.

assertFalse($x)

Fail if $x is true.

assertNull($x)

Fail if $x is set.

assertNotNull($x)

Fail if $x not set.

assertIsA($x, $t)

Fail if $x is not the class or type $t.

assertNotA($x, $t)

Fail if $x is of the class or type $t.

assertEqual($x, $y)

Fail if $x == $y is false.

assertNotEqual($x, $y)

Fail if $x == $y is true.

assertWithinMargin($x, $y, $m)

Fail if abs($x - $y) < $m is false.

assertOutsideMargin($x, $y, $m)

Fail if abs($x - $y) < $m is true.

assertIdentical($x, $y)

Fail if $x == $y is false or a type mismatch.

assertNotIdentical($x, $y)

Fail if $x == $y is true and types match.

assertReference($x, $y)

Fail unless $x and $y are the same variable.

assertClone($x, $y)

Fail unless $x and $y are identical copies.

assertPattern($p, $x)

Fail unless the regex $p matches $x.

assertNoPattern($p, $x)

Fail if the regex $p matches $x.

expectError($x)

Swallow any upcoming matching error.

assert($e)

Fail on failed expectation object $e.

Table C.3. SimpleText Content Assertions

Assertion

Description

assertTitle($title)

Pass if title is an exact match.

assertText($text)

Pass if matches visible and "alt" text.

assertNoText($text)

Pass if doesn't match visible and "alt" text.

assertPattern($pattern)

A Perl pattern match against the page content.

assertNoPattern($pattern)

A Perl pattern match to not find content.

assertLink($label)

Pass if a link with this text is present.

assertNoLink($label)

Pass if no link with this text is present.

assertLinkById($id)

Pass if a link with this id attribute is present.

assertNoLinkById($id)

Pass if no link with this id attribute is present.

assertField($name, $value)

Pass if an input tag with this name has this value.

assertFieldById($id, $value)

Pass if an input tag with this id has this value.

assertResponse($codes)

Pass if HTTP response matches this list.

assertMime($types)

Pass if MIME type is in this list.

assertAuthentication($protocol)

Pass if the current challenge is this protocol.

assertNoAuthentication()

Pass if there is no current challenge.

assertRealm($name)

Pass if the current challenge realm matches.

assertHeader($header, $content)

Pass if a header was fetched matching this value.

assertNoHeader($header)

Pass if a header was not fetched.

assertCookie($name, $value)

Pass if there is currently a matching cookie.

assertNoCookie($name)

Pass if there is currently no cookie of this name.

Table C.4. SimpleTest Navigation Methods

Method

Description

getUrl()

Get the current location.

get($url, $parameters)

Send a GET request with these parameters.

post($url, $parameters)

Send a POST request with these parameters.

head($url, $parameters)

Send a HEAD request without replacing the page content.

retry()

Reload the last request.

back()

Like the browser back button.

forward()

Like the browser forward button.

authenticate($name, $password)

Retry after a challenge.

restart()

Restart the browser as if a new session.

getCookie($name)

Get the cookie value for the current context.

ageCookies($interval)

Age current cookies prior to a restart.

clearFrameFocus()

Go back to treating all frames as one page.

clickSubmit($label)

Click the first button with this label.

clickSubmitByName($name)

Click the button with this name attribute.

clickSubmitById($id)

Click the button with this ID attribute.

clickImage($label, $x, $y)

Click an input tag of type image by title or alt text.

clickImageByName($name, $x, $y)

Click an input tag of type image by name.

clickImageById($id, $x, $y)

Click an input tag of type image by ID attribute.

submitFormById($id)

Submit a form without the submit value.

clickLink($label, $index)

Click an anchor by the visible label text.

clickLinkById($id)

Click an anchor by the ID attribute.

getFrameFocus()

Get the name of the currently selected frame.

setFrameFocusByIndex($choice)

Focus on a frame counting from 1.

setFrameFocus($name)

Focus on a frame by name.

Table C.5. SimpleTest Request Modifiers

Request modifier

Description

getTransportError()

Get the last socket error.

showRequest()

Dump the outgoing request.

showHeaders()

Dump the incoming headers.

showSource()

Dump the raw HTML page content.

ignoreFrames()

Do not load framesets.

setCookie($name, $value)

Set a cookie from now on.

addHeader($header)

Always add this header to the request.

setMaximumRedirects($max)

Stop after this many redirects.

setConnectionTimeout($timeout)

Kill the connection after this time between bytes.

useProxy($proxy, $name, $password)

Make requests via this proxy URL.

Install Hooks

In Chapter 10, I covered the Drupal installation process. Table C-6 lists hooks that are specific to the .install file.

Table C.6. Install Hooks

Hook

Description

hook_install()

Perform setup tasks when the module is installed.

hook_uninstall()

Remove any information that the module sets.

hook_update_N()

Perform a single update. For each patch that requires a database change, add a new hook_update_N() that will be called by update.php. The database updates are numbered sequentially according to the version of Drupal you are compatible with.

hook_schema()

Define the current version of the database schema.

hook_modules_installed()

Perform necessary actions after modules are installed.

hook_modules_uninstalled()

Perform necessary actions after modules are uninstalled.

hook_install_tasks()

Return an array of tasks to be performed by an installation profile.

hook_install_tasks_alter()

Alter the full list of installation tasks.

hook_requirements()

Check installation requirements and do status reporting.

hook_enable()

Perform necessary actions after module is enabled. The hook is called every time the module is enabled.

hook_disable()

Perform necessary actions before module is disabled. The hook is called every time the module is disabled.

Schema API

A Drupal schema definition is an array structure representing one or more tables and their related keys and indexes. A schema is defined by hook_schema(), which usually lives in a modulename.install file.

By implementing hook_schema() and specifying the tables your module declares, you can easily create and drop these tables on all supported database engines. You don't have to deal with the different SQL dialects for table creation and alteration of the supported database engines.

Drupal defines a number of structures for content management. The most ubiquitous is the node, which is the core container for content types. All Drupal-managed content extends from the node.

The field framework allows the user to create custom content types that extend the Drupal content even farther for specialized needs.

But there are other managed objects, such as users, blocks, and taxonomy terms, for which there are many functions to query, modify, and delete these objects.

These Drupal-managed objects are handy and create a powerful, extensible platform, but might be too cumbersome if you merely want to store away a small piece of data, or even a large set that would not necessarily be considered traditional Drupal content.

In other words, you might want to add tables to the Drupal database that you will manage in your modules and that the Drupal core doesn't really need to know or care about.

Creating database tables in a database-agnostic way is a bit tricky, but fortunately, Drupal's Schema API makes it possible. Instead of passing CREATE TABLE or ALTER TABLE queries directly to the database, we use a syntax that's consistent with other Drupal structures.

Schema API Classes

Drupal has a number of classes that can be used to access your schema information in a database-agnostic way. The classes are listed in Table C-7.

Table C.7. Schema API Classes

Name

Description

DatabaseSchema

Implements QueryPlaceholderInterface to provide a generic means of accessing the Schema API.

DatabaseSchemaObjectDoesNotExistException

Throws exception if an object being modified doesn't exist yet.

DatabaseSchemaObjectExistsException

Throws exception if an object being created already exists.

DatabaseSchema_mysql
DatabaseSchema_pgsql
DatabaseSchema_sqlite
DatabaseSchema_sqlsvr

Implements features specific to a particular database engine.

Schema API Functions and Methods

If you will be creating custom schemas for your module, you'll probably create schemas using the schema hook in the .install file. In addition, there are a number of functions and methods that allow you to manipulate the schema in your code. These are listed in Table C-8.

Table C.8. Schema API Functions and Methods

Name

Description

db_add_field

Adds a new field to a table.

db_add_index

Adds an index.

db_add_primary_key

Adds a primary key to a database table.

db_add_unique_key

Adds a unique key.

db_change_field

Changes a field definition.

db_create_table

Creates a new table from a Drupal table definition.

db_drop_field

Drops a field.

db_drop_index

Drops an index.

db_drop_primary_key

Drops the primary key of a database table.

db_drop_table

Drops a table.

db_drop_unique_key

Drops a unique key.

db_field_exists

Checks if a column exists in the given table.

db_field_names

Returns an array of field names from an array of key/index column specifiers.

db_field_set_default

Sets the default value for a field.

db_field_set_no_default

Sets a field to have no default value.

db_find_tables

Finds all tables that are like the specified base table name.

db_index_exists

Checks if an index exists in the given table.

db_rename_table

Renames a table.

db_table_exists

Checks if a table exists.

drupal_get_schema

Gets the schema definition of a table, or the whole database schema.

drupal_get_schema_unprocessed

Returns the unprocessed and unaltered version of a module's schema.

drupal_install_schema

Creates all tables in a module's hook_schema() implementation.

drupal_schema_fields_sql

Retrieves a list of fields from a table schema. The list is suitable for use in a SQL query.

drupal_uninstall_schema

Removes all tables that a module defines in its hook_schema().

drupal_write_record

Saves a record to the database based upon the schema.

hook_schema

Defines the current version of the database schema. See next section.

Schema Hook

The best way to create schemas for your module is to create an array that defines all aspects of your data structures and use the schema hook in your .install file. I discuss this topic in Chapter 10.

The schema hook should return an array with a key for each table the module defines. The following keys are defined:

  • 'description': A string in non-markup plain text describing this table and its purpose. References to other tables should be enclosed in curly-brackets. For example, the node_revisions table description field might contain "Stores per-revision title and body data for each {node}."

  • 'fields': An associative array ('fieldname' => specification) that describes the table's database columns. The specification is also an array. The following specification parameters are defined:

    • 'description': A string in non-markup plain text describing this field and its purpose. References to other tables should be enclosed in curly-brackets.

    • 'type': The generic data type: 'char', 'varchar', 'text', 'blob', 'int', 'float', 'numeric', 'serial', 'date', 'datetime' or 'time'. Most types just map to the corresponding database engine-specific data types. Use 'serial' for auto-incrementing fields. This will expand to 'INT auto_increment' on MySQL.

    • 'serialize': A Boolean indicating whether the field will be stored as a serialized string.

    • 'size': The data size: 'tiny', 'small', 'medium', 'normal', 'big'. This is a hint about the largest value the field will store and determines which of the database engine-specific data types will be used (e.g., on MySQL, TINYINT vs. INT vs. BIGINT). 'normal', the default, selects the base type (e.g., on MySQL, INT, VARCHAR, BLOB, etc.). Not all sizes are available for all data types. See DatabaseSchema::getFieldTypeMap() for possible combinations.

    • 'not null': If true, no NULL values will be allowed in this database column. Defaults to false.

    • 'default': The field's default value. The PHP type of the value matters: '', '0', and 0 are all different. If you specify '0' as the default value for a type 'int' field it will not work because '0' is a string containing the character "zero", not an integer.

    • 'length': The maximal length of a type 'char', 'varchar' or 'text' field. Ignored for other field types.

    • 'unsigned': A Boolean indicating whether a type ('int', 'float', and 'numeric' only) is signed or unsigned. Defaults to FALSE. Ignored for other field types.

    • 'precision', 'scale': For type 'numeric' fields, indicates the precision (total number of significant digits) and scale (decimal digits right of the decimal point). Both values are mandatory. Ignored for other field types.

    All parameters apart from 'type' are optional except that type 'numeric' columns must specify 'precision' and 'scale'.

  • 'primary key': An array of one or more key column specifiers (see below) that form the primary key.

  • 'unique keys': An associative array of unique keys ('keyname' => specification). Each specification is an array of one or more key column specifiers (see below) that form a unique key on the table.

  • 'foreign keys': An associative array of relations ('my_relation' => specification). Each specification is an array containing the name of the referenced table ('table'), and an array of column mappings ('columns'). Column mappings are defined by key pairs ('source_column' => 'referenced_column').

  • 'indexes': An associative array of indexes ('indexname' => specification). Each specification is an array of one or more key column specifiers (see below) that form an index on the table.

A key column specifier is either a string naming a column or an array of two elements: column name and length, specifying a prefix of the named column.

Globals

The Drupal core uses certain global variables in the construction of a page. Global variables are discussed in Chapter 3. The globals used in the core are listed in Table C-9.

Table C.9. Drupal Core Global Variables

Name

Location

Description

$base_path

includes/bootstrap.inc

The base path of the Drupal installation. This will at least default to '/'.

$base_root

includes/bootstrap.inc

The root URL of the host, excluding the path.

$base_theme_info

includes/theme.inc

An array of objects that represent the base theme.

$base_url

includes/bootstrap.inc

The base URL of the Drupal installation.

$channel

modules/aggregator/aggregator.parser.inc

An associative array containing title, link, description, and other keys. Links should be an absolute URL.

$conf

./settings.php

Site configuration values defined in the global settings file.

$conf

includes/bootstrap.inc

Array of persistent variables stored in 'variable' table.

$cookie_domain

includes/bootstrap.inc

The domain to be used for session cookies. For hosts such as 'localhost' or those that expos only an IP address, the cookie domain will not be set.

$databases

./settings.php

Array of database connections.

$drupal_test_info

modules/simpletest/drupal_web_test_case.php

Global variable that holds information about the tests being run.

$element

modules/aggregator/aggregator.parser.inc

Structured array describing the data to be rendered.

$forum_topic_list_header

modules/forum/forum.module

An array of forum topic header information.

$image

modules/aggregator/aggregator.parser.inc

Current image tag used by aggregator parsing.

$installed_profile

includes/bootstrap.inc

The name of the profile that has just been installed.

$item

modules/aggregator/aggregator.parser.inc

General string or array.

$items

modules/aggregator/aggregator.parser.inc

Array of items used by aggregator.

$language

includes/bootstrap.inc

An object containing the information for the active interface language. It represents the language the user interface textual elements such as titles, labels or messages, are to be displayed in.

$language_content

modules/field/field.multilingual.inc

An object containing the information for the active content language. It is used by the Field API as a default value when no language is specified to select the field translation to be displayed.

$language_url

includes/locale.inc

An object containing the information for the active URL language. It is used as a default value by URL-related functions such as l() when no language is explicitly specified.

$menu_admin

includes/path.inc

Boolean indicating that a menu administrator is running a menu access check.

$multibyte

includes/unicode.inc

The current multibyte mode. Possible values: UNICODE_ERROR, UNICODE_SINGLEBYTE, UNICODE_MULTIBYTE.

$pager_limits

includes/pager.inc

Array of the number of items per page for each pager. The array index is the pager element index (0 by default).

$pager_page_array

includes/pager.inc

Array of current page numbers for each pager.

$pager_total

includes/pager.inc

Array of the total number of pages for each pager. The array index is the pager element index (0 by default).

$pager_total_items

includes/pager.inc

Array of the total number of items for each pager. The array index is the pager element index (0 by default).

$tag

modules/aggregator/aggregator.parser.inc

Active tag name.

$theme

includes/theme.inc

Active theme name.

$theme_engine

includes/theme.inc

The theme engine related to the active theme.

$theme_info

includes/theme.inc

Active theme object.

$theme_key

includes/theme.inc

Name of the active theme.

$theme_path

includes/theme.inc

The path to the active theme.

$timers

includes/bootstrap.inc

Timers that have been created by timer_start().

$update_free_access

sites/default/settings.php

Allows the update.php script to be run when not logged in as administrator. Be sure to set to FALSE for production systems!

$user

includes/bootstrap.inc

An object representing the currently logged-in user. Contains preferences and other user information.

Field CRUD API

The Field CRUD API is for creating fields, bundles, and instances. Fields are covered in Chapter 9. Functions and methods are shown in Table C-10.

Table C.10. Field CRUD API Functions and Methods

Name

Description

field_create_field

Creates a field.

field_create_instance

Creates an instance of a field, binding it to a bundle.

field_delete_field

Marks a field and its instances and data for deletion.

field_delete_instance

Marks a field instance and its data for deletion.

field_read_field

Reads a single field record directly from the database.

field_read_fields

Reads in fields that match an array of conditions.

field_read_instance

Reads a single instance record directly from the database.

field_read_instances

Reads in field instances that match an array of conditions.

field_update_field

Updates a field.

field_update_instance

Updates an instance of a field.

hook_field_create_field

Acts on a field being created.

hook_field_create_instance

Acts on a field instance being created.

hook_field_delete_field

Acts on a field being deleted.

hook_field_delete_instance

Acts on a field instance being deleted.

hook_field_purge_field

Acts when a field record is being purged.

hook_field_purge_field_instance

Acts when a field instance is being purged.

hook_field_read_field

Acts on field records being read from the database.

hook_field_read_instance

Acts on a field record being read from the database.

hook_field_storage_purge

Removes field storage information when field data is purged.

hook_field_storage_purge_field

Removes field storage information when a field record is purged.

hook_field_storage_purge_field_instance

Removes field storage information when a field instance is purged.

hook_field_update_field

Acts on a field being updated.

hook_field_update_forbid

Forbids a field update.

hook_field_update_instance

Acts on a field instance being updated.

_field_write_instance

Stores an instance record in the field configuration database.

Field Attach API

The Field Attach API allows you to operate on Field API data that has been attached to Drupal entities. Fields are covered in Chapter 9. Functions and methods are listed in Table C-11.

Table C.11. Field Attach API Functions and Methods

Name

Description

field_attach_create_bundle

Notifies field.module that a new bundle was created.

field_attach_delete

Deletes field data for an existing entity. This deletes all revisions of field data for the entity.

field_attach_delete_bundle

Notifies field.module that a bundle was deleted.

field_attach_delete_revision

Deletes field data for a single revision of an existing entity. The passed entity must have a revision id attribute.

field_attach_form

Adds form elements for all fields for an entity to a form structure.

field_attach_form_validate

Performs field validation against form-submitted field values.

field_attach_insert

Saves field data for a new entity.

field_attach_load

Loads fields for the current revisions of a group of entities.

field_attach_load_revision

Loads all fields for previous versions of a group of entities.

field_attach_prepare_translation

Prepares an entity for translation.

field_attach_prepare_view

Prepares field data prior to display.

field_attach_preprocess

Populates the template variables with the field values available for rendering.

field_attach_presave

Performs necessary operations just before field data gets saved.

field_attach_rename_bundle

Notifies field.module that a bundle was renamed.

field_attach_submit

Performs necessary operations on field data submitted by a form.

field_attach_update

Saves field data for an existing entity.

field_attach_validate

Performs field validation against the field data in an entity.

field_attach_view

Returns a renderable array for the fields on an entity.

hook_field_attach_create_bundle

Acts on field_attach_create_bundle().

hook_field_attach_delete

Acts on field_attach_delete().

hook_field_attach_delete_bundle

Acts on field_attach_delete_bundle().

hook_field_attach_delete_revision

Acts on field_attach_delete_revision().

hook_field_attach_form

Acts on field_attach_form().

hook_field_attach_insert

Acts on field_attach_insert().

hook_field_attach_load

Acts on field_attach_load().

hook_field_attach_prepare_translation_alter

Performs alterations on field_attach_prepare_translation().

hook_field_attach_preprocess_alter

Alters field_attach_preprocess() variables.

hook_field_attach_presave

Acts on field_attach_presave().

hook_field_attach_purge

Acts on field_purge_data().

hook_field_attach_rename_bundle

Acts on field_attach_rename_bundle().

hook_field_attach_submit

Acts on field_attach_submit().

hook_field_attach_update

Acts on field_attach_update().

hook_field_attach_validate

Acts on field_attach_validate().

hook_field_attach_view_alter

Performs alterations on field_attach_view() or field_view_field().

hook_field_available_languages_alter

Alters field_available_languages() values.

hook_field_language_alter

Performs alterations on field_language() values.

_field_invoke

Invokes a field hook.

_field_invoke_default

Invokes field.module's version of a field hook.

_field_invoke_get_instances

Helpers for _field_invoke(): retrieves a list of instances to operate on.

_field_invoke_multiple

Invokes a field hook across fields on multiple entities.

_field_invoke_multiple_default

Invokes field.module's version of a field hook on multiple entities.

Drush Reference

Drush, the Drupal shell, is a handy tool for performing certain tasks in Drupal from the command line. Installing and running Drush is covered in Appendix A. Table C-12 shows a list of core Drush commands.

Note that Drush is an extensible tool, so other modules and themes can add functionality to an installed version of Drush.

Table C.12. Drush Commands

Command

Description

batch-process

Processes operations in the specified batch set.

cache-clear

Clears a specific cache, or all drupal caches.

cc

Clears a specific cache, or all drupal caches.

cli

Enters a new shell optimized for drush use. All .bashrc customizations are still available.

core-readme

Displays README.txt.

core-rsync

Rsyncs the Drupal tree to or from another server using ssh. Relative paths start from the Drupal root folder if a site alias is used; otherwise they start from the current working directory.

cron

Runs all cron hooks.

dd

Returns the file system path for projects and themes and other key folders. Used by the cli command for handy commands cdd and lsd.

dis

Disables one or more modules or themes.

dl

Downloads core Drupal and contributed modules and themes. It will automatically figure out which project version you want based on its latest release, or you may specify a particular version.

en

Enables one or more modules or themes.

eval

Evaluates arbitrary php code after bootstrapping Drupal.

field-clone

Clones a field and all its instances.

field-create

Creates fields and instances. Returns URLs for field editing.

field-delete

Deletes a field and its instances.

field-info

Views information about fields, field_types, and widgets.

field-update

Returns URL for field editing web page.

help

Prints this help message. See drush help help for more options.

php-eval

Evaluates arbitrary php code after bootstrapping Drupal.

php-script

Runs the given php script(s) after a full Drupal bootstrap. A useful alternative to eval command when your php is lengthy or you can't be bothered to figure out bash quoting.

pm-info

Shows info for one or more projects.

pm-releases

Views all releases for a given project (modules, themes, profiles, translations). Useful for deciding which version to install or update.

pm-uninstall

Uninstalls one or more modules. Modules must be disabled first.

pm-updatecode-notify-pending-db-updates

Notifies of pending db updates.

rf

Refreshes update status information.

sa

Prints site alias records for all known site aliases and local sites.

search-index

Indexes the remaining search items without wiping the index.

search-reindex

Forces the search index to be rebuilt.

search-status

Shows how many items remain to be indexed out of the total.

si

Installs Drupal along with modules, themes, and configuration using the specified install profile. Be careful with this command; it will drop your database and create a fresh one.

sm

Shows a list of available modules and themes.

sql-conf

Prints database connection details using print_r().

sql-connect

A string for connecting to the DB.

sql-drop

Drop all tables in a given database.

sql-dump

Prints the whole database to STDOUT or saves to a file.

sql-sync

Copies source database to target database using rsync.

sqlc

Opens a SQL command-line interface using Drupal's credentials.

sqlq

Execute a query against the site database.

status

Provides a birds-eye view of the current Drupal installation, if any.

status

Provides a birds-eye view of the current Drupal installation, if any.

sm

Shows a list of available modules and themes.

sup

Executes a major version upgrade for Drupal core and enabled contributed modules. Command will download next version of Drupal and all available contributed modules that have releases (if not already downloaded).

sync

Rsyncs the Drupal tree to/from another server using ssh. Relative paths start from the Drupal root folder if a site alias is used; otherwise they start from the current working directory.

topic

Reads detailed documentation on a given topic.

ublk

Blocks the specified user(s).

ucan

Cancels a user account with the specified name.

ucrt

Creates a user account with the specified name.

uinf

Displays information about a user identified by username, uid or e-mail address.

uli

Displays a one-time login link for the given user account (defaults to uid 1).

uninstall

Uninstalls one or more modules.

up

Displays available update information and allow updating of all installed projects to the specified version (or latest by default), followed by applying any database updates required (as with running update.php).

upc

Displays available update information and allow updating of all installed project code to the specified version (or latest by default).

updatedb-batch-process

Performs update functions.

updb

Executes the update.php process from the command line.

upwd

Sets or resets the password for the user account with the specified name.

urol

Adds a role to the specified user accounts.

urrol

Removes a role from the specified user accounts.

uublk

Unblocks the specified user(s).

vdel

Deletes a variable.

vget

Gets a list of some or all site variables and values.

vset

Sets a variable.

wd

Deletes watchdog messages.

wd-list

Shows available message types and severity levels. A prompt will ask for a choice to show watchdog messages.

ws

Shows watchdog messages.

Drush has a set of global options that work on most commands. See Table C-13.

Table C.13. Drush Global Options

Option

Description

-r , --root=

Drupal root directory to use (default: current directory).

-l , --uri=http://example.com

URI of the Drupal site to use (only needed in multisite environments).

-v, --verbose

Displays extra information about the command.

-d, --debug

Displays even more information, including internal messages.

-q, --quiet

Hides all output.

-y, --yes

Assumes "yes" as answer to all prompts.

-n, --no

Assumes "no" as answer to all prompts.

-s, --simulate

Simulates all relevant actions (doesn't actually change the system).

-i, --include

A list of paths to search for drush commands.

-c, --config

Specifies a config file to use. See example.drushrc.php.

-u, --user

Specifies a user to login; may be a name or a number.

-b, --backend

Hides all output and returns structured data (internal use only).

-p, --pipe

Emits a compact representation of the command for scripting.

--nocolor

Suppresses color highlighting on log messages.

--show-passwords

Shows database passwords in commands that display connection information.

-h, --help

This help system.

--php

The absolute path to your PHP interpreter, if not 'php' in the path.

Summary

The Drupal core is a powerful framework for managing content and displaying it for visitors to your web site. The power derives from the rich set of functions and classes that comprise the Drupal API.

In this appendix, I have listed tables of common API functions that I use a lot. Still, the best place to find information about any part of the Drupal API is http://api.drupal.org.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5