This document provides an overview of the various API components available in Drupal 7, including the module system, database abstraction layer, menu system, form generation, file management system, field API, search system, node access system, theme system, and other core APIs. It describes key classes, functions, and hooks for each component.
1. Drupal 7 API Components
Table of Contents
Drupal 7 API Components................................................................................................................1
Preface.............................................................................................................................................1
Module System (Hooks)...................................................................................................................1
Functions & methods...................................................................................................................2
Database Abstraction Layer.............................................................................................................9
SELECT.......................................................................................................................................9
INSERT, UPDATE and DELETE................................................................................................11
Transactions...............................................................................................................................11
Classes......................................................................................................................................12
Interfaces...................................................................................................................................14
Functions & methods.................................................................................................................14
Constants..................................................................................................................................14
Menu System.................................................................................................................................14
Functions & methods.................................................................................................................15
Constants..................................................................................................................................18
Groups.......................................................................................................................................19
Form Generation............................................................................................................................19
The $form_state keys are:.........................................................................................................20
Functions & methods.................................................................................................................21
File Management System...............................................................................................................24
Fields on the file object:.............................................................................................................24
Functions & methods.................................................................................................................24
Constants..................................................................................................................................26
Field API.........................................................................................................................................26
Classes......................................................................................................................................27
Functions & methods.................................................................................................................27
Constants..................................................................................................................................28
Search System...............................................................................................................................28
Functions & methods.................................................................................................................28
Node Access System.....................................................................................................................29
Functions & methods.................................................................................................................29
Theme System...............................................................................................................................30
See also.....................................................................................................................................31
Functions & methods.................................................................................................................31
Constants.......................................................................................................................................36
Global variables..............................................................................................................................37
Preface
The following technical document is compiled from the official Drupal API information published at
http://api.drupal.org/api/drupal/7
It is intended for use by developers aiming to master Drupal 7.
Module System (Hooks)
Allow modules to interact with the Drupal core.
Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is
2. named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and
"bar" is the name of the hook. Each hook has a defined set of parameters and a specified result
type.
To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow
intervention from modules, it determines which modules implement a hook and calls that hook in
all enabled modules that implement it.
The available hooks to implement are explained here in the Hooks section of the developer
documentation. The string "hook" is used as a placeholder for the module name in the hook
definitions. For example, if the module file is called example.module, then hook_help() as
implemented by that module would be defined as example_help().
The example functions included are not part of the Drupal core, they are just models that you can
modify. Only the hooks implemented within modules are executed when running Drupal.
See also the themeable group page.
Functions & methods
Name
hook_actions_delete
hook_action_info
hook_action_info_alter
hook_admin_paths
hook_admin_paths_alter
hook_aggregator_fetch
hook_aggregator_fetch_info
hook_aggregator_parse
hook_aggregator_parse_info
hook_aggregator_process
hook_aggregator_process_info
hook_aggregator_remove
hook_ajax_render_alter
hook_archiver_info
hook_archiver_info_alter
hook_batch_alter
hook_block_configure
hook_block_info
hook_block_info_alter
hook_block_list_alter
hook_block_save
Description
Executes code after an action is deleted.
Declares information about actions.
Alters the actions declared by another module.
Define administrative paths.
Redefine administrative paths defined by other
modules.
Implement this hook to create an alternative
fetcher for aggregator module.
Implement this hook to expose the title and a
short description of your fetcher.
Implement this hook to create an alternative
parser for aggregator module.
Implement this hook to expose the title and a
short description of your parser.
Implement this hook to create a processor for
aggregator module.
Implement this hook to expose the title and a
short description of your processor.
Implement this hook to remove stored data if a
feed is being deleted or a feed's items are being
removed.
Alter the commands that are sent to the user
through the AJAX framework.
Declare archivers to the system.
Alter archiver information declared by other
modules.
Alter batch information before a batch is
processed.
Define a configuration form for a block.
Define all blocks provided by the module.
Change block definition before saving to the
database.
Act on blocks prior to rendering.
Save the configuration options
fromhook_block_configure().
6. Name
Description
updated.
Perform necessary actions after modules are
hook_modules_disabled
disabled.
Perform necessary actions after modules are
hook_modules_enabled
enabled.
Perform necessary actions after modules are
hook_modules_installed
installed.
Perform necessary actions after modules are
hook_modules_uninstalled
uninstalled.
Alter the registry of modules implementing a
hook_module_implements_alter
hook.
Allow modules to react to language settings
hook_multilingual_settings_changed
changes.
hook_node_access
Control access to a node.
Set permissions for a node to be written to the
hook_node_access_records
database.
Alter permissions for a node before it is written to
hook_node_access_records_alter
the database.
hook_node_delete
Respond to node deletion.
Inform the node access system what permissions
hook_node_grants
the user has.
Alter user access rules when trying to view, edit
hook_node_grants_alter
or delete a node.
hook_node_info
Define module-provided node types.
hook_node_insert
Respond to creation of a new node.
hook_node_load
Act on nodes being loaded from the database.
hook_node_operations
Add mass node operations.
Act on a node object about to be shown on the
hook_node_prepare
add/edit form.
hook_node_presave
Act on a node being inserted or updated.
hook_node_revision_delete
Respond to deletion of a node revision.
hook_node_search_result
Act on a node being displayed as a search result.
Act on a node after validated form values have
hook_node_submit
been copied to it.
hook_node_type_delete
Respond to node type deletion.
hook_node_type_insert
Respond to node type creation.
hook_node_type_update
Respond to node type updates.
hook_node_update
Respond to updates to a node.
hook_node_update_index
Act on a node being indexed for searching.
Perform node validation before a node is created
hook_node_validate
or updated.
Act on a node that is being assembled before
hook_node_view
rendering.
hook_node_view_alter
Alter the results of node_view().
Allow modules to modify the OpenID request
hook_openid
parameters.
Allow modules to declare OpenID discovery
hook_openid_discovery_method_info
methods.
hook_openid_discovery_method_info_alter
Allow modules to alter discovery methods.
Allow modules to declare OpenID normalization
hook_openid_normalization_method_info
methods.
hook_openid_normalization_method_info_alter Allow modules to alter normalization methods.
Allow modules to act upon a successful OpenID
hook_openid_response
login.
9. Name
hook_user_login
hook_user_logout
hook_user_operations
hook_user_presave
hook_user_role_delete
hook_user_role_insert
hook_user_role_update
hook_user_update
hook_user_view
hook_user_view_alter
hook_validate
hook_verify_update_archive
hook_view
hook_watchdog
hook_xmlrpc
hook_xmlrpc_alter
module_hook
module_hook_info
module_implements
module_implements_write_cache
module_invoke
module_invoke_all
sample_search_conditions_callback
Description
database.
The user just logged in.
The user just logged out.
Add mass user operations.
A user account is about to be created or updated.
Inform other modules that a user role has been
deleted.
Inform other modules that a user role has been
added.
Inform other modules that a user role has been
updated.
A user account was updated.
The user's account information is being displayed.
The user was built; the module may modify the
structured content.
Perform node validation before a node is created
or updated.
Verify an archive after it has been downloaded
and extracted.
Display a node.
Log an event message
Register XML-RPC callbacks.
Alters the definition of XML-RPC methods before
they are called.
Determine whether a module implements a hook.
Retrieve a list of what hooks are explicitly
declared.
Determine which modules are implementing a
hook.
Writes the hook implementation cache.
Invoke a hook in a particular module.
Invoke a hook in all enabled modules that
implement it.
An example conditions callback function for
search.
includes/module.inc, line 532
Database Abstraction Layer
Allow the use of different database servers using the same code base.
Drupal provides a database abstraction layer to provide developers with the ability to support
multiple database servers easily. The intent of this layer is to preserve the syntax and power of
SQL as much as possible, but also allow developers a way to leverage more complex functionality
in a unified way. It also provides a structured interface for dynamically constructing queries when
appropriate, and enforcing security checks and similar good practices.
The system is built atop PHP's PDO (PHP Data Objects) database API and inherits much of its
syntax and semantics.
SELECT
Most Drupal database SELECT queries are performed by a call to db_query() or
db_query_range(). Module authors should also consider using the PagerDefault Extender for
10. queries that return results that need to be presented on multiple pages, and the Tablesort Extender
for generating appropriate queries for sortable tables.
For example, one might wish to return a list of the most recent 10 nodes authored by a given user.
Instead of directly issuing the SQL query
<?php
SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
?>
one would instead call the Drupal functions:
<?php
$result = db_query_range('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', 0, 10, array(':uid' => $uid));
foreach ($result as $record) {
// Perform operations on $node->title, etc. here.
}
?>
Curly braces are used around "node" to provide table prefixing via
DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled out into an argument
passed to db_query() so that SQL injection attacks from user input can be caught and nullified. The
LIMIT syntax varies between database servers, so that is abstracted into db_query_range()
arguments. Finally, note the PDO-based ability to iterate over the result set using foreach ().
All queries are passed as a prepared statement string. A prepared statement is a "template" of a
query that omits literal or variable values in favor of placeholders. The values to place into those
placeholders are passed separately, and the database driver handles inserting the values into the
query in a secure fashion. That means you should never quote or string-escape a value to be
inserted into the query.
There are two formats for placeholders: named and unnamed. Named placeholders are strongly
preferred in all cases as they are more flexible and self-documenting. Named placeholders should
start with a colon ":" and can be followed by one or more letters, numbers or underscores.
Named placeholders begin with a colon followed by a unique string. Example:
<?php
SELECT nid, title FROM {node} WHERE uid=:uid;
?>
":uid" is a placeholder that will be replaced with a literal value when the query is executed. A given
placeholder label cannot be repeated in a given query, even if the value should be the same. When
using named placeholders, the array of arguments to the query must be an associative array
where keys are a placeholder label (e.g., :uid) and the value is the corresponding value to use. The
array may be in any order.
Unnamed placeholders are simply a question mark. Example:
<?php
SELECT nid, title FROM {node} WHERE uid=?;
?>
In this case, the array of arguments must be an indexed array of values to use in the exact same
order as the placeholders in the query.
11. Note that placeholders should be a "complete" value. For example, when running a LIKE query the
SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is
incorrect:
<?php
SELECT nid, title FROM {node} WHERE title LIKE :title%;
?>
It should instead read:
<?php
SELECT nid, title FROM {node} WHERE title LIKE :title;
?>
and the value for :title should include a % as appropriate. Again, note the lack of quotation marks
around :title. Because the value is not inserted into the query as one big string but as an explicitly
separate value, the database server knows where the query ends and a value begins. That is
considerably more secure against SQL injection than trying to remember which values need
quotation marks and string escaping and which don't.
INSERT, UPDATE and DELETE
INSERT, UPDATE, and DELETE queries need special care in order to behave consistently across
all different databases. Therefore, they use a special object-oriented API for defining a query
structurally. For example, rather than:
<?php
INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body');
?>
one would instead write:
<?php
$fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
db_insert('node')->fields($fields)->execute();
?>
This method allows databases that need special data type handling to do so, while also allowing
optimizations such as multi-insert queries. UPDATE and DELETE queries have a similar pattern.
Transactions
Drupal also supports transactions, including a transparent fallback for databases that do not
support transactions. To start a new transaction, simply call $txn = db_transaction(); in your own
code. The transaction will remain open for as long as the variable $txn remains in scope. When
$txn is destroyed, the transaction will be committed. If your transaction is nested inside of another
then Drupal will track each transaction and only commit the outer-most transaction when the last
transaction object goes out out of scope, that is, all relevant queries completed successfully.
Example:
<?php
function my_transaction_function() {
// The transaction opens here.
$txn = db_transaction();
12. try {
$id = db_insert('example')
->fields(array(
'field1' => 'mystring',
'field2' => 5,
))
->execute();
my_other_function($id);
return $id;
}
catch (Exception $e) {
// Something went wrong somewhere, so roll back now.
$txn->rollback();
// Log the exception to watchdog.
watchdog_exception('type', $e);
}
// $txn goes out of scope here.
Unless the transaction was rolled back, it
// gets automatically commited here.
}
function my_other_function($id) {
// The transaction is still open here.
if ($id % 2 == 0) {
db_update('example')
->condition('id', $id)
->fields(array('field2' => 10))
->execute();
}
}
?>
@link http://drupal.org/developing/api/database
Classes
Name
Database
DatabaseCondition
DatabaseConnection
DatabaseConnectionNotDefinedException
Description
Primary front-controller for the
database system.
Generic class for a series of conditions
in a query.
Base Database API class.
Exception thrown if an undefined
database connection is requested.
DatabaseConnection_mysql
DatabaseConnection_pgsql
DatabaseConnection_sqlite
DatabaseDriverNotSpecifiedException
Specific SQLite implementation of
DatabaseConnection.
Exception thrown if no driver is
specified for a database connection.
13. Name
Description
Default implementation of
DatabaseStatementBase
DatabaseStatementInterface.
Empty implementation of a database
DatabaseStatementEmpty
statement.
An implementation of
DatabaseStatementPrefetch
DatabaseStatementInterface that
prefetches all data.
Specific SQLite implementation of
DatabaseStatement_sqlite
DatabaseConnection.
A wrapper class for creating and
DatabaseTransaction
managing database transactions.
Exception thrown when a commit()
DatabaseTransactionCommitFailedException
function fails.
Exception to deny attempts to
DatabaseTransactionExplicitCommitNotAllowedException
explicitly manage transactions.
Exception thrown when a savepoint or
DatabaseTransactionNameNonUniqueException
transaction name occurs twice.
Exception for when popTransaction() is
DatabaseTransactionNoActiveException
called with no active transaction.
General class for an abstracted DELETE
DeleteQuery
operation.
SQLite specific implementation of
DeleteQuery_sqlite
DeleteQuery.
Exception thrown if an insert query
FieldsOverlapException
specifies a field twice.
General class for an abstracted INSERT
InsertQuery
query.
InsertQuery_mysql
InsertQuery_pgsql
SQLite specific implementation of
InsertQuery_sqlite
InsertQuery.
Exception thrown for merge queries
InvalidMergeQueryException
that do not make semantic sense.
General class for an abstracted MERGE
MergeQuery
query operation.
Exception thrown if an insert query
NoFieldsException
doesn't specify insert or default fields.
Query
Base class for query builders.
SelectQuery
Query builder for SELECT statements.
The base extender class for Select
SelectQueryExtender
queries.
SelectQuery_pgsql
SQLite specific query builder for
SelectQuery_sqlite
SELECT statements.
General class for an abstracted
TruncateQuery
TRUNCATE operation.
TruncateQuery_mysql
SQLite specific implementation of
TruncateQuery_sqlite
TruncateQuery.
General class for an abstracted
UpdateQuery
UPDATE operation.
UpdateQuery_pgsql
SQLite specific implementation of
UpdateQuery_sqlite
UpdateQuery.
14. Interfaces
Name
DatabaseStatementInterface
QueryAlterableInterface
QueryConditionInterface
QueryExtendableInterface
QueryPlaceholderInterface
SelectQueryInterface
Description
A prepared statement.
Interface for a query that can be manipulated via an alter hook.
Interface for a conditional clause in a query.
Interface for extendable query objects.
Interface for a query that accepts placeholders.
Interface definition for a Select Query object.
Functions & methods
Name
db_and
db_autoload
db_close
db_condition
db_delete
db_driver
db_escape_field
db_escape_table
db_insert
db_like
db_merge
db_next_id
db_or
db_query
db_query_range
db_query_temporary
db_select
db_set_active
db_transaction
db_truncate
db_update
db_xor
Description
Returns a new DatabaseCondition, set to "AND" all conditions together.
Autoload callback for the database system.
Closes the active database connection.
Returns a new DatabaseCondition, set to the specified conjunction.
Returns a new DeleteQuery object for the active database.
Retrieves the name of the currently active database driver.
Restricts a dynamic column or constraint name to safe characters.
Restricts a dynamic table name to safe characters.
Returns a new InsertQuery object for the active database.
Escapes characters that work as wildcard characters in a LIKE pattern.
Returns a new MergeQuery object for the active database.
Retrieves a unique id.
Returns a new DatabaseCondition, set to "OR" all conditions together.
Executes an arbitrary query string against the active database.
Executes a query against the active database, restricted to a range.
Executes a query string and saves the result set to a temporary table.
Returns a new SelectQuery object for the active database.
Sets a new active database.
Returns a new transaction object for the active database.
Returns a new TruncateQuery object for the active database.
Returns a new UpdateQuery object for the active database.
Returns a new DatabaseCondition, set to "XOR" all conditions
together.
Constants
Name
Description
The name by which to obtain a lock for retrive the next insert
POSTGRESQL_NEXTID_LOCK
id.
includes/database/database.inc, line 13
Menu System
Define the navigation menus, and route page requests to code based on URLs.
The Drupal menu system drives both the navigation system from a user perspective and the
callback system that Drupal uses to respond to URLs passed from the browser. For this reason, a
good understanding of the menu system is fundamental to the creation of complex modules.
Drupal's menu system follows a simple hierarchy defined by paths. Implementations of
hook_menu() define menu items and assign them to paths (which should be unique). The menu
15. system aggregates these items and determines the menu hierarchy from the paths. For example, if
the paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system would form the structure:
•
a
•
a/b
•
•
•
•
a/b/c/d
a/b/h
e
f/g
Note that the number of elements in the path does not necessarily determine the depth of the
menu item in the tree.
When responding to a page request, the menu system looks to see if the path requested by the
browser is registered as a menu item with a callback. If not, the system searches up the menu tree
for the most complete match with a callback it can find. If the path a/b/i is requested in the tree
above, the callback for a/b would be used.
The found callback function is called with any arguments specified in the "page arguments"
attribute of its menu item. The attribute must be an array. After these arguments, any remaining
components of the path are appended as further arguments. In this way, the callback for a/b above
could respond to a request for a/b/i differently than a request for a/b/j.
For an illustration of this process, see page_example.module.
Access to the callback functions is also protected by the menu system. The "access callback" with
an optional "access arguments" of each menu item is called before the page callback proceeds. If
this returns TRUE, then access is granted; if FALSE, then access is denied. Menu items may omit
this attribute to use the value provided by an ancestor item.
In the default Drupal interface, you will notice many links rendered as tabs. These are known in the
menu system as "local tasks", and they are rendered as tabs by default, though other
presentations are possible. Local tasks function just as other menu items in most respects. It is
convention that the names of these tasks should be short verbs if possible. In addition, a "default"
local task should be provided for each set. When visiting a local task's parent menu item, the
default local task will be rendered as if it is selected; this provides for a normal tab user experience.
This default task is special in that it links not to its provided path, but to its parent item's path
instead. The default task's path is only used to place it appropriately in the menu hierarchy.
Everything described so far is stored in the menu_router table. The menu_links table holds the
visible menu links. By default these are derived from the same hook_menu definitions, however
you are free to add more with menu_link_save().
Functions & methods
Name
drupal_help_arg
menu_build_tree
menu_cache_clear
menu_cache_clear_all
menu_contextual_links
Description
Generates elements for the $arg array in the help
hook.
Build a menu tree, translate links, and check access.
Clears the cached cached data for a single named
menu.
Clears all cached menu data. This should be called
any time broad changes might have been made to
the router items or menu links.
Retrieve contextual links for a system object based
on registered local tasks.
17. Name
menu_set_active_trail
menu_set_custom_theme
menu_set_item
menu_tab_root_path
menu_tail_to_arg
menu_tree
menu_tree_all_data
menu_tree_check_access
menu_tree_collect_node_links
menu_tree_data
menu_tree_output
menu_tree_page_data
menu_unserialize
template_preprocess_menu_tree
theme_menu_link
theme_menu_local_action
theme_menu_local_task
theme_menu_local_tasks
theme_menu_tree
_menu_build_tree
_menu_check_access
_menu_clear_page_cache
_menu_delete_item
_menu_find_router_path
_menu_item_localize
_menu_link_build
_menu_link_map_translate
_menu_link_move_children
_menu_link_parents_set
_menu_link_translate
_menu_load_objects
Description
Sets or gets the active trail (path to menu tree root)
of the current page.
Sets a custom theme for the current page, if there is
one.
Replaces the statically cached item for a given path.
Returns the router path, or the path of the parent
tab of a default local task.
Renders a menu tree based on the current path.
Get the data structure representing a named menu
tree.
Check access and perform other dynamic
operations for each link in the tree.
Recursive helper function - collect node links.
Build the data representing a menu tree.
Returns a rendered menu tree.
Get the data structure representing a named menu
tree, based on the current page.
The menu system uses serialized arrays stored in
the database for arguments. However, often these
need to change according to the current path. This
function unserializes such an array and does the
necessary change.
Preprocesses the rendered tree
for theme_menu_tree().
Returns HTML for a menu link and submenu.
Returns HTML for a single local action link.
Returns HTML for a single local task link.
Returns renderable local tasks.
Returns HTML for a wrapper for a menu sub-tree.
Build a menu tree.
Check access to a menu item using the access
callback
Helper function to clear the page and block caches
at most twice per page load.
Helper function for menu_link_delete; deletes a
single menu link.
Find the router path which will serve this path.
Localize the router item title using t() or another
callback.
Builds a link from a router item.
This function translates the path elements in the
map using any to_arg helper function. These
functions take an argument and return an object.
Seehttp://drupal.org/node/109153 for more
information.
Update the children of a menu link that's being
moved.
Helper function that sets the p1..p9 values for a
menu link being saved.
This function is similar to _menu_translate() but
does link-specific preparation such as always calling
to_arg functions
Loads objects into the map as defined in the
$item['load_functions'].
18. Name
_menu_navigation_links_rebuild
_menu_router_build
_menu_router_cache
_menu_router_save
_menu_set_expanded_menus
_menu_site_is_offline
_menu_translate
_menu_tree_check_access
_menu_tree_data
_menu_update_parental_status
Description
Helper function to build menu links for the items in
the menu router.
Helper function to build the router table based on
the data from hook_menu.
Helper function to store the menu router if we have
it in memory.
Helper function to save data
from menu_router_build() to the router table.
Helper function to update a list of menus with
expanded items
Checks whether the site is in maintenance mode.
Handles dynamic path translation and menu access
control.
Recursive helper function
for menu_tree_check_access()
Recursive helper function to build the data
representing a menu tree.
Check and update the has_children status for the
parent of a link.
Constants
Name
MENU_ACCESS_DENIED
MENU_CALLBACK
MENU_CONTEXT_INLINE
MENU_CONTEXT_NONE
MENU_CONTEXT_PAGE
MENU_CREATED_BY_ADMIN
MENU_DEFAULT_LOCAL_TASK
MENU_FOUND
MENU_IS_LOCAL_ACTION
MENU_IS_LOCAL_TASK
MENU_IS_ROOT
MENU_LINKS_TO_PARENT
MENU_LOCAL_ACTION
MENU_LOCAL_TASK
MENU_MAX_DEPTH
MENU_MAX_PARTS
MENU_MODIFIED_BY_ADMIN
MENU_NORMAL_ITEM
Description
Internal menu status code -- Menu item access is
denied.
Menu type -- A hidden, internal callback, typically
used for API calls.
Internal menu flag: Local task should be displayed
inline.
Internal menu flag: Invisible local task.
Internal menu flag: Local task should be displayed
in page context.
Internal menu flag -- menu item was created by
administrator.
Menu type -- The "default" local task, which is
initially active.
Internal menu status code -- Menu item was found.
Internal menu flag -- menu item is a local action.
Internal menu flag -- menu item is a local task.
Internal menu flag -- menu item is the root of the
menu tree.
Internal menu flag -- menu item links back to its
parent.
Menu type -- An action specific to the parent,
usually rendered as a link.
Menu type -- A task specific to the parent item,
usually rendered as a tab.
The maximum depth of a menu links tree - matches
the number of p columns.
The maximum number of path elements for a menu
callback
Internal menu flag -- menu item can be modified by
administrator.
Menu type -- A "normal" menu item that's shown in
menu and breadcrumbs.
19. Name
MENU_NOT_FOUND
MENU_SITE_OFFLINE
MENU_SITE_ONLINE
MENU_SUGGESTED_ITEM
MENU_VISIBLE_IN_BREADCRUMB
MENU_VISIBLE_IN_TREE
Description
Internal menu status code -- Menu item was not
found.
Internal menu status code -- Menu item inaccessible
because site is offline.
Internal menu status code -- Everything is working
fine.
Menu type -- A normal menu item, hidden until
enabled by an administrator.
Internal menu flag -- menu item is visible in the
breadcrumb.
Internal menu flag -- menu item is visible in the
menu tree.
Groups
Name
Menu context
types
Menu flags
Description
Flags for use in the "context" attribute of menu router items.
Flags for use in the "type" attribute of menu items.
Menu item definitions provide one of these constants, which are shortcuts for
Menu item types
combinations of the above flags.
Menu status codes Status codes for menu callbacks.
Menu tree
Menu tree
parameters
includes/menu.inc, line 9
Form Generation
Functions to enable the processing and display of HTML forms.
Drupal uses these functions to achieve consistency in its form processing and presentation, while
simplifying code and reducing the amount of HTML that must be explicitly generated by modules.
The primary function used with forms is drupal_get_form(), which is used for forms presented
interactively to a user. Forms can also be built and submitted programmatically without any user
input using the drupal_form_submit() function.
drupal_get_form() handles retrieving, processing, and displaying a rendered HTML form for
modules automatically.
Here is an example of how to use drupal_get_form() and a form builder function:
<?php
$form = drupal_get_form('my_module_example_form');
...
function my_module_example_form($form, &$form_state) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function my_module_example_form_validate($form, &$form_state) {
// Validation logic.
20. }
function my_module_example_form_submit($form, &$form_state) {
// Submission logic.
}
?>
Or with any number of additional arguments:
<?php
$extra = "extra";
$form = drupal_get_form('my_module_example_form', $extra);
...
function my_module_example_form($form, &$form_state, $extra) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => $extra,
);
return $form;
}
?>
The $form argument to form-related functions is a structured array containing the elements and
properties of the form. For information on the array components and format, and more detailed
explanations of the Form API workflow, see the Form API reference and the Form API section of
the handbook. In addition, there is a set of Form API tutorials in the Form Example Tutorial which
provide basics all the way up through multistep forms.
In the form builder, validation, submission, and other form functions, $form_state is the primary
influence on the processing of the form and is passed by reference to most functions, so they use
it to communicate with the form system and each other.
The $form_state keys are:
•
•
•
•
'values': An associative array of values submitted to the form. The validation functions and
submit functions use this array for nearly all their decision making. (Note that #tree
determines whether the values are a flat array or an array whose structure parallels the
$form array.)
'rebuild': If the submit function sets $form_state['rebuild'] to TRUE, submission is not
completed and instead the form is rebuilt using any information that the submit function has
made available to the form builder function via $form_state. This is commonly used for
wizard-style multi-step forms, add-more buttons, and the like. For further information see
drupal_build_form().
'redirect': a URL that will be used to redirect the form on submission. See
drupal_redirect_form() for complete information.
'storage': $form_state['storage'] is not a special key, and no specific support is provided for
it in the Form API, but by tradition it was the location where application-specific data was
stored for communication between the submit, validation, and form builder functions,
especially in a multi-step-style form. Form implementations may use any key(s) within
$form_state (other than the keys listed here and other reserved ones used by Form API
internals) for this kind of storage. The recommended way to ensure that the chosen key
doesn't conflict with ones used by the Form API or other modules is to use the module
name as the key name or a prefix for the key name. For example, the Node module uses
$form_state['node'] in node editing forms to store information about the node being edited,
and this information stays available across successive clicks of the "Preview" button as well
as when the "Save" button is finally clicked.
21. •
•
•
•
'temporary': Since values for all non-reserved keys in $form_state persist throughout a
multistep form sequence, the Form API provides the 'temporary' key for modules to use for
communicating information across form-related functions during a single page request only.
There is no use-case for this functionality in core.
'triggering_element': (read-only) The form element that triggered submission. This is the
same as the deprecated $form_state['clicked_button']. It is the element that caused
submission, which may or may not be a button (in the case of AJAX forms.) This is often
used to distinguish between various buttons in a submit handler, and is also used in AJAX
handlers.
'cache': The typical form workflow involves two page requests. During the first page
request, a form is built and returned for the user to fill in. Then the user fills the form in and
submits it, triggering a second page request in which the form must be built and processed.
By default, $form and $form_state are built from scratch during each of these page
requests. In some special use-cases, it is necessary or desired to persist the $form and
$form_state variables from the initial page request to the one that processes the
submission. A form builder function can set 'cache' to TRUE to do this. One example where
this is needed is to handle AJAX submissions, so ajax_process_form() sets this for all forms
that include an element with a #ajax property. (In AJAX, the handler has no way to build the
form itself, so must rely on the cached version created on each page load, so it's a classic
example of this use case.) Note that the persistence of $form and $form_state across
successive submissions of a multi-step form happens automatically regardless of the value
for 'cache'.
'input': The array of values as they were submitted by the user. These are raw and
unvalidated, so should not be used without a thorough understanding of security
implications. In almost all cases, code should use the data in the 'values' array exclusively.
The most common use of this key is for multi-step forms that need to clear some of the user
input when setting 'rebuild'.
Functions & methods
Name
date_validate
drupal_build_form
drupal_form_submit
drupal_get_form
drupal_prepare_form
drupal_process_form
drupal_rebuild_form
drupal_redirect_form
drupal_retrieve_form
drupal_validate_form
form_builder
Description
Validates the date type to stop dates like February
30, 2006.
Build and process a form based on a form id.
Retrieves, populates, and processes a form.
Wrapper for drupal_build_form() for use when
$form_state is not needed.
Prepares a structured form array by adding
required elements, executing any hook_form_alter
functions, and optionally inserting a validation
token to prevent tampering.
Processes a form submission.
Constructs a new $form from the information in
$form_state.
Redirects the user to a URL after a form has been
processed.
Retrieves the structured array that defines a given
form.
Validates user-submitted form data from the
$form_state using the validate functions defined
in a structured form array.
Walk through the structured form array, adding
any required properties to each element and
mapping the incoming input data to the proper
elements. Also, execute any #process handlers
attached to a specific element.
24. Name
Description
Helper function to handle the convoluted logic of
_form_element_triggered_scripted_submission
button click detection.
_form_options_flatten
Helper function for form_options_flatten().
_form_set_class
Sets a form element's class attribute.
Performs validation on form elements. First
ensures required fields are completed,
_form_validate
#maxlength is not exceeded, and selected
options were in the list of options given to the
user. Then calls user-defined validators.
includes/form.inc, line 23
File Management System
Common file handling functions.
Fields on the file object:
•
•
•
•
•
•
•
•
fid: File ID
uid: The {users}.uid of the user who is associated with the file.
filename: Name of the file with no path components. This may differ from the basename of
the filepath if the file is renamed to avoid overwriting an existing file.
uri: URI of the file.
filemime: The file's MIME type.
filesize: The size of the file in bytes.
status: A bitmapped field indicating the status of the file. The first 8 bits are reserved for
Drupal core. The least significant bit indicates temporary (0) or permanent (1). Temporary
files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs.
timestamp: UNIX timestamp for the date the file was added to the database.
Functions & methods
Name
drupal_chmod
drupal_dirname
drupal_mkdir
drupal_realpath
drupal_rmdir
drupal_tempnam
drupal_unlink
file_build_uri
file_copy
file_create_filename
file_create_htaccess
file_create_url
file_default_scheme
file_delete
Description
Set the permissions on a file or directory.
Gets the name of the directory from a given
path.
Creates a directory using Drupal's default mode.
Returns the absolute path of a file or directory
Remove a directory.
Creates a file with a unique filename in the
specified directory.
Deletes a file.
Given a relative path, construct a URI into
Drupal's default files location.
Copies a file to a new location and adds a file
record to the database.
Create a full file path from a directory and
filename.
Creates an .htaccess file in the given directory.
Creates a web-accessible URL for a stream to an
external or local file.
Get the default file stream implementation.
Delete a file and its database record.
26. Name
file_usage_delete
file_usage_list
file_validate
file_validate_extensions
file_validate_image_resolution
file_validate_is_image
file_validate_name_length
file_validate_size
file_valid_uri
Description
Removes a record to indicate that a module is no
longer using a file.
Determines where a file is used.
Check that a file meets the criteria specified by
the validators.
Check that the filename ends with an allowed
extension.
Verify that image dimensions are within the
specified maximum and minimum.
Check that the file is recognized
byimage_get_info() as an image.
Check for files with names longer than we can
store in the database.
Check that the file's size is below certain limits.
Determine whether the URI has a valid scheme
for file API operations.
Constants
Name
FILE_CREATE_DIRECTORY
FILE_EXISTS_ERROR
Description
Flag used by file_prepare_directory() -- create directory if not present.
Flag for dealing with existing files: Do nothing and return FALSE.
Flag for dealing with existing files: Appends number until name is
FILE_EXISTS_RENAME
unique.
FILE_EXISTS_REPLACE
Flag for dealing with existing files: Replace the existing file.
FILE_MODIFY_PERMISSION Flag used by file_prepare_directory() -- file permissions may be
S
changed.
FILE_STATUS_PERMANENT
Indicates that the file is permanent and should not be deleted.
includes/file.inc, line 18
Field API
Attach custom data fields to Drupal entities.
The Field API allows custom data fields to be attached to Drupal entities and takes care of storing,
loading, editing, and rendering field data. Any entity type (node, user, etc.) can use the Field API to
make itself "fieldable" and thus allow fields to be attached to it. Other modules can provide a user
interface for managing custom fields via a web browser as well as a wide and flexible variety of
data type, form element, and display format capabilities.
•
Data structures: Field, Instance, Bundle.
•
Field Types API. Defines field types, widget types, and display formatters. Field modules
use this API to provide field types like Text and Node Reference along with the associated
form elements and display formatters.
Field CRUD API. Create, updates, and deletes fields, bundles (a.k.a. "content types"), and
instances. Modules use this API, often in hook_install(), to create custom data structures.
Field Attach API. Connects entity types to the Field API. Field Attach API functions load,
store, generate Form API structures, display, and perform a variety of other functions for
field data connected to individual entities. Fieldable entity types like node and user use this
API to make themselves fieldable.
Field Info API. Exposes information about all fields, instances, widgets, and related
information defined by or with the Field API.
•
•
•
27. •
•
•
Field Storage API. Provides a pluggable back-end storage system for actual field data. The
default implementation, field_sql_storage.module, stores field data in the local SQL
database.
Field API bulk data deletion. Cleans up after bulk deletion operations such
asfield_delete_field() and field_delete_instance().
Field language API. Provides native multilingual support for the Field API.
Classes
Name
Description
FieldUpdateForbiddenException Exception class thrown by hook_field_update_forbid().
Functions & methods
Name
field_access
field_associate_fields
field_bundle_settings
field_cache_clear
field_cron
field_extract_bundle
field_extra_fields_get_display
field_filter_xss
field_flush_caches
field_get_default_value
field_get_display
field_get_items
field_has_data
field_help
field_modules_disabled
field_modules_enabled
field_modules_uninstalled
field_theme
field_view_field
field_view_mode_settings
field_view_value
template_preprocess_field
template_process_field
_field_extra_fields_pre_render
_field_filter_items
_field_filter_xss_allowed_tags
_field_filter_xss_display_allowed_tags
Description
Determine whether the user has access to a given
field.
Allows a module to update the database for fields
and columns it controls.
Gets or sets administratively defined bundle
settings.
Clear the field info and field data caches.
Implements hook_cron().
Helper function to extract the bundle name of
from a bundle object.
Returns the display settings to use for pseudofields in a given view mode.
Like filter_xss_admin(), but with a shorter list of
allowed tags.
Implements hook_flush_caches().
Helper function to get the default value for a field
on an entity.
Returns the display settings to use for an instance
in a given view mode.
Returns the field items in the language they
currently would be displayed.
Determine whether a field has any data.
Implements hook_help().
Implements hook_modules_disabled().
Implements hook_modules_enabled().
Implements hook_modules_uninstalled().
Implements hook_theme().
Returns a renderable array for the value of a
single field in an entity.
Returns view mode settings in a given bundle.
Returns a renderable array for a single field value.
Theme preprocess function for theme_field()
andfield.tpl.php.
Theme process function for theme_field()
andfield.tpl.php.
Pre-render callback to adjust weights and visibility
of non-field elements.
Helper function to filter out empty field values.
List of tags allowed by field_filter_xss().
Human-readable list of allowed tags, for display in
28. Name
_field_sort_items
_field_sort_items_helper
_field_sort_items_value_helper
Description
help texts.
Helper function to sort items in a field according
to user drag-n-drop reordering.
Sort function for items order. (copied
formelement_sort(), which acts on #weight keys)
Same as above, using ['_weight']['#value']
Constants
Name
FIELD_BEHAVIOR_CUSTOM
FIELD_BEHAVIOR_DEFAULT
FIELD_BEHAVIOR_NONE
FIELD_CARDINALITY_UNLIMITED
FIELD_LOAD_CURRENT
FIELD_LOAD_REVISION
Description
TODO
TODO
TODO
Value for $field['cardinality'] property to indicate it can
hold an unlimited number of values.
Age argument for loading the most recent version of an
entity's field data with field_attach_load().
Age argument for loading the version of an entity's field
data specified in the entity with field_attach_load().
modules/field/field.module, line 28
Search System
The Drupal search interface manages a global search mechanism.
Modules may plug into this system to provide searches of different types of data. Most of the
system is handled by search.module, so this must be enabled for all of the search features to work.
There are three ways to interact with the search system:
Specifically for searching nodes, you can implement hook_node_update_index() and
hook_node_search_result(). However, note that the search system already indexes all visible
output of a node, i.e. everything displayed normally by hook_view() and hook_node_view(). This is
usually sufficient. You should only use this mechanism if you want additional, non-visible data to be
indexed.
Implement hook_search_info(). This will create a search tab for your module on the /search page
with a simple keyword search form. You will also need to implement hook_search_execute() to
perform the search.
Implement hook_update_index(). This allows your module to use Drupal's HTML indexing
mechanism for searching full text efficiently.
If your module needs to provide a more complicated search form, then you need to implement it
yourself without hook_search_info(). In that case, you should define it as a local task (tab) under
the /search page (e.g. /search/mymodule) so that users can easily find it.
Functions & methods
Name
hook_search_access
hook_search_admin
hook_search_execute
hook_search_info
hook_search_preprocess
hook_search_reset
Description
Define access to a custom search routine.
Add elements to the search settings form.
Execute a search for a set of key words.
Define a custom search type.
Preprocess text for search.
Take action when the search index is going to be rebuilt.
29. Name
hook_search_status
hook_update_index
sample_search_conditions_c
allback
search_box
search_box_form_submit
search_data
search_excerpt
Description
Report the status of indexing.
Update the search index for this module.
An example conditions callback function for search.
Form builder; Output a search form for the search block's search
box.
Process a block search form submission.
Performs a search by callinghook_search_execute().
Returns snippets from a piece of text, with certain keywords
highlighted. Used for formatting search results.
Builds a search form.
Update the full-text search index for a particular item.
search_form
search_index
template_preprocess_search
Process variables for search-block-form.tpl.php.
_block_form
modules/search/search.module, line 897
Node Access System
The node access system determines who can do what to which nodes.
In determining access rights for a node, node_access() first checks whether the user has the
"bypass node access" permission. Such users have unrestricted access to all nodes. user 1 will
always pass this check.
Next, all implementations of hook_node_access() will be called. Each implementation may
explicitly allow, explicitly deny, or ignore the access request. If at least one module says to deny
the request, it will be rejected. If no modules deny the request and at least one says to allow it, the
request will be permitted.
If all modules ignore the access request, then the node_access table is used to determine access.
All node access modules are queried using hook_node_grants() to assemble a list of "grant IDs"
for the user. This list is compared against the table. If any row contains the node ID in question (or
0, which stands for "all nodes"), one of the grant IDs returned, and a value of TRUE for the
operation in question, then access is granted. Note that this table is a list of grants; any matching
row is sufficient to grant access to the node.
In node listings, the process above is followed except that hook_node_access() is not called on
each node for performance reasons and for proper functioning of the pager system. When adding
a node listing to your module, be sure to use a dynamic query created by db_select() and add a
tag of "node_access" to ensure that only nodes to which the user has access are retrieved.
Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access() will block
access to the node. Therefore, implementers should take care to not deny access unless they
really intend to. Unless a module wishes to actively deny access it should return
NODE_ACCESS_IGNORE (or simply return nothing) to allow other modules or the node_access
table to control access.
To see how to write a node access module of your own, see node_access_example.module.
Functions & methods
Name
hook_node_access
hook_node_access_records
hook_node_access_records_alter
Description
Control access to a node.
Set permissions for a node to be written to the
database.
Alter permissions for a node before it is written to
the database.
30. Name
hook_node_grants
hook_node_grants_alter
node_access
node_access_acquire_grants
node_access_grants
node_access_needs_rebuild
node_access_rebuild
node_access_view_all_nodes
node_access_write_grants
node_list_permissions
node_node_access
node_permissions_get_configured_types
node_query_entity_field_access_alter
node_query_node_access_alter
_node_access_rebuild_batch_finished
_node_access_rebuild_batch_operation
_node_query_node_access_alter
Description
Inform the node access system what permissions
the user has.
Alter user access rules when trying to view, edit or
delete a node.
Determine whether the current user may perform
the given operation on the specified node.
Gets the list of node access grants and writes them
to the database.
Fetch an array of permission IDs granted to the
given user ID.
Flag / unflag the node access grants for rebuilding,
or read the current value of the flag.
Rebuild the node access database. This is
occasionally needed by modules that make
system-wide changes to access levels.
Determines whether the user has a global viewing
grant for all nodes.
Writes a list of grants to the database, deleting any
previously saved ones.
Helper function to generate standard node
permission list for a given type.
Implements hook_node_access().
Returns an array of node types that should be
managed by permissions.
Implements hook_query_TAG_alter().
Implements hook_query_TAG_alter().
Post-processing for node_access_rebuild_batch.
Batch operation for node_access_rebuild_batch.
Helper for node access functions.
modules/node/node.module, line 2726
Theme System
Functions and templates that present output to the user, and can be implemented by themes.
Drupal's presentation layer is a pluggable system known as the theme layer. Each theme can take
control over most of Drupal's output, and has complete control over the CSS.
Inside Drupal, the theme layer is utilized by the use of the theme() function, which is passed the
name of a component (the theme hook) and an array of variables. For example, theme('table',
array('header' => $header, 'rows' => $rows)); Additionally, the theme() function can take an array of
theme hooks, which can be used to provide 'fallback' implementations to allow for more specific
control of output. For example, the function: theme(array('table__foo', 'table'), $variables) would
look to see if 'table__foo' is registered anywhere; if it is not, it would 'fall back' to the generic 'table'
implementation. This can be used to attach specific theme functions to named objects, allowing the
themer more control over specific types of output.
As of Drupal 6, every theme hook is required to be registered by the module that owns it, so that
Drupal can tell what to do with it and to make it simple for themes to identify and override the
behavior for these calls.
The theme hooks are registered via hook_theme(), which returns an array of arrays with
information about the hook. It describes the arguments the function or template will need, and
provides defaults for the template in case they are not filled in. If the default implementation is a
function, by convention it is named theme_HOOK().
Each module should provide a default implementation for theme_hooks that it registers. This
31. implementation may be either a function or a template; if it is a function it must be specified via
hook_theme(). By convention, default implementations of theme hooks are named theme_HOOK.
Default template implementations are stored in the module directory.
Drupal's default template renderer is a simple PHP parsing engine that includes the template and
stores the output. Drupal's theme engines can provide alternate template engines, such as
XTemplate, Smarty and PHPTal. The most common template engine is PHPTemplate (included
with Drupal and implemented in phptemplate.engine, which uses Drupal's default template
renderer.
In order to create theme-specific implementations of these hooks, themes can implement their own
version of theme hooks, either as functions or templates. These implementations will be used
instead of the default implementation. If using a pure .theme without an engine, the .theme is
required to implement its own version of hook_theme() to tell Drupal what it is implementing;
themes utilizing an engine will have their well-named theming functions automatically registered for
them. While this can vary based upon the theme engine, the standard set by phptemplate is that
theme functions should be named THEMENAME_HOOK. For example, for Drupal's default theme
(Bartik) to implement the 'table' hook, the phptemplate.engine would find bartik_table().
The theme system is described and defined in theme.inc.
End of "defgroup themeable".
See also
theme()
hook_theme()
Functions & methods
Name
theme_admin_block
theme_admin_block_content
theme_admin_page
theme_aggregator_block_item
theme_aggregator_categorize_items
theme_aggregator_feed_source
theme_aggregator_item
theme_aggregator_page_opml
theme_aggregator_page_rss
theme_aggregator_summary_item
theme_aggregator_summary_items
theme_aggregator_wrapper
theme_authorize_message
theme_authorize_report
theme_block
theme_block_admin_display_form
Description
Returns HTML for an administrative block for
display.
Returns HTML for the content of an
administrative block.
Returns HTML for an administrative page.
Returns HTML for an individual feed item for
display in the block.
Returns HTML for the aggregator page list form
for assigning categories.
Implemented using the aggregator-feedsource.tpl.php template.
Implemented using the aggregatoritem.tpl.phptemplate.
Prints the OPML page for a feed.
Prints the RSS page for a feed.
Implemented using the aggregator-summaryitem.tpl.php template.
Implemented using the aggregator-summaryitems.tpl.php template.
Implemented using the aggregatorwrapper.tpl.phptemplate.
Returns HTML for a single log message from
theauthorize.php batch operation.
Returns HTML for a report of the results from an
operation run via authorize.php.
Implemented using the block.tpl.php template.
Implemented using the block-admin-display-
37. Global variables
Name
$base_path
$base_root
$base_theme_info
$base_url
$channel
$conf
$cookie_domain
$custom_theme
$databases
$drupal_test_info
$element
$forum_topic_list_header
$image
$installed_profile
$item
$items
$language
$language_content
$language_url
$menu_admin
$multibyte
$pager_limits
$pager_page_array
$pager_total
$pager_total_items
$tag
$theme
$theme_engine
$theme_info
Location
Description
The base path of the Drupal
developer/globals.php
installation.
The root URL of the host, excluding the
developer/globals.php
path.
An array of objects that represent the
developer/globals.php
base theme.
The base URL of the Drupal
developer/globals.php
installation.
An associative array containing title,
developer/globals.php
link, description and other keys.
Array of persistent variables stored in
developer/globals.php
'variable' table.
The domain to be used for session
developer/globals.php
cookies.
Name of custom theme to override
developer/globals.php
default theme.
Array of database connections.
developer/globals.php
modules/simpletest/drupal_ Global variable that holds information
web_test_case.php
about the tests being run.
Structured array describing the data to
developer/globals.php
be rendered.
An array of forum topic header
developer/globals.php
information.
Current image tag used by aggregator
developer/globals.php
parsing.
The name of the profile that has just
developer/globals.php
been installed.
General string or array.
developer/globals.php
Array of items used by aggregator.
developer/globals.php
An object containing the information
developer/globals.php
for the active interface language.
An object containing the information
developer/globals.php
for the active content language.
An object containing the information
developer/globals.php
for the active URL language.
Boolean indicating that a menu
administrator is running a menu access
developer/globals.php
check.
The current multibyte mode.
developer/globals.php
Array of the number of items per page
developer/globals.php
for each pager.
Array of current page numbers for each
developer/globals.php
pager.
Array of the total number of pages for
developer/globals.php
each pager.
Array of the total number of items for
developer/globals.php
each pager.
Active tag name.
developer/globals.php
Name of the active theme.
developer/globals.php
The theme engine related to the active
developer/globals.php
theme.
Active theme object.
developer/globals.php