- •Contents at a Glance
- •Contents
- •Foreword
- •About the Authors
- •About the Technical Reviewers
- •Acknowledgments
- •Introduction
- •Technology Stack
- •Core
- •Administrative Interface
- •Modules
- •How Drupal Works
- •What Is Drupal?
- •Hooks
- •Themes
- •Nodes
- •Fields
- •Blocks
- •File Layout
- •Serving a Request
- •The Web Server’s Role
- •The Bootstrap Process
- •Processing a Request
- •Theming the Data
- •Summary
- •Writing a Module
- •Creating the Files
- •Implementing a Hook
- •Adding Module-Specific Settings
- •Defining Your Own Administration Section
- •Presenting a Settings Form to the User
- •Validating User-Submitted Settings
- •Storing Settings
- •Using Drupal’s variables Table
- •Retrieving Stored Values with variable_get()
- •Further Steps
- •Summary
- •Hooks, Actions, and Triggers
- •Understanding Events and Triggers
- •Understanding Actions
- •The Trigger User Interface
- •Your First Action
- •Assigning the Action
- •Changing Which Triggers an Action Supports
- •Actions That Support Any Trigger
- •Advanced Actions
- •Using the Context in Actions
- •How the Trigger Module Prepares the Context
- •Changing Existing Actions with action_info_alter()
- •Establishing the Context
- •How Actions Are Stored
- •The actions Table
- •Action IDs
- •Calling an Action Directly with actions_do()
- •Defining Your Own Triggers with hook_trigger_info()
- •Adding Triggers to Existing Hooks
- •Summary
- •The Menu System
- •Callback Mapping
- •Mapping URLs to Functions
- •Creating a Menu Item
- •Page Callback Arguments
- •Page Callbacks in Other Files
- •Adding a Link to the Navigation Block
- •Menu Nesting
- •Access Control
- •Title Localization and Customization
- •Defining a Title Callback
- •Wildcards in Menu Items
- •Basic Wildcards
- •Wildcards and Page Callback Parameters
- •Using the Value of a Wildcard
- •Wildcards and Parameter Replacement
- •Passing Additional Arguments to the Load Function
- •Special, Predefined Load Arguments: %map and %index
- •Building Paths from Wildcards Using to_arg() Functions
- •Special Cases for Wildcards and to_arg() Functions
- •Altering Menu Items from Other Modules
- •Altering Menu Links from Other Modules
- •Kinds of Menu Items
- •Common Tasks
- •Assigning Callbacks Without Adding a Link to the Menu
- •Displaying Menu Items As Tabs
- •Hiding Existing Menu Items
- •Using menu.module
- •Common Mistakes
- •Summary
- •Working with Databases
- •Defining Database Parameters
- •Understanding the Database Abstraction Layer
- •Connecting to the Database
- •Performing Simple Queries
- •Retrieving Query Results
- •Getting a Single Value
- •Getting Multiple Rows
- •Using the Query Builder and Query Objects
- •Getting a Limited Range of Results
- •Getting Results for Paged Display
- •Other Common Queries
- •Inserts and Updates with drupal_write_record()
- •The Schema API
- •Using Module .install Files
- •Creating Tables
- •Using the Schema Module
- •Field Type Mapping from Schema to Database
- •Textual
- •Varchar
- •Char
- •Text
- •Numerical
- •Integer
- •Serial
- •Float
- •Numeric
- •Date and Time: Datetime
- •Binary: Blob
- •Declaring a Specific Column Type with mysql_type
- •Maintaining Tables
- •Deleting Tables on Uninstall
- •Changing Existing Schemas with hook_schema_alter()
- •Modifying Other Modules’ Queries with hook_query_alter()
- •Connecting to Multiple Databases Within Drupal
- •Using a Temporary Table
- •Writing Your Own Database Driver
- •Summary
- •Working with Users
- •The $user Object
- •Testing If a User Is Logged In
- •Introduction to user hooks
- •Understanding hook_user_view($account, $view_mode)
- •The User Registration Process
- •Using profile.module to Collect User Information
- •The Login Process
- •Adding Data to the $user Object at Load Time
- •Providing User Information Categories
- •External Login
- •Summary
- •Working with Nodes
- •So What Exactly Is a Node?
- •Not Everything Is a Node
- •Creating a Node Module
- •Creating the .install File
- •Creating the .info File
- •Creating the .module File
- •Providing Information About Our Node Type
- •Modifying the Menu Callback
- •Defining Node-Type–Specific Permissions with hook_permission()
- •Limiting Access to a Node Type with hook__node_access()
- •Customizing the Node Form for Our Node Type
- •Validating Fields with hook_validate()
- •Saving Our Data with hook_insert()
- •Keeping Data Current with hook_update()
- •Cleaning Up with hook_delete()
- •Modifying Nodes of Our Type with hook_load()
- •Using hook_view()
- •Manipulating Nodes That Are Not Our Type with hook_node_xxxxx()
- •How Nodes Are Stored
- •Creating a Node Type with Custom Content Types
- •Restricting Access to Nodes
- •Defining Node Grants
- •What Is a Realm?
- •What Is a Grant ID?
- •The Node Access Process
- •Summary
- •Working with Fields
- •Creating Content Types
- •Adding Fields to a Content Type
- •Creating a Custom Field
- •Adding Fields Programmatically
- •Summary
- •The Theme System
- •Themes
- •Installing an Off-the-Shelf Theme
- •Building a Theme
- •The .info File
- •Adding Regions to Your Theme
- •Adding CSS Files to Your Theme
- •Adding JavaScript Files
- •Adding Settings to Your Theme
- •Understanding Template Files
- •The Big Picture
- •The html.php.tpl File
- •The page.tpl.php File
- •The region.tpl.php File
- •The node.tpl.php File
- •The field.tpl.php File
- •The block.tpl.php File
- •Overriding Template Files
- •Other Template Files
- •Introducing the theme() Function
- •An Overview of How theme() Works
- •Overriding Themable Items
- •Overriding with Template Files
- •Adding and Manipulating Template Variables
- •Using the Theme Developer Module
- •Summary
- •Working with Blocks
- •What Is a Block?
- •Block Configuration Options
- •Block Placement
- •Defining a Block
- •Using the Block Hooks
- •Building a Block
- •Enabling a Block When a Module Is Installed
- •Block Visibility Examples
- •Displaying a Block to Logged-In Users Only
- •Displaying a Block to Anonymous Users Only
- •Summary
- •The Form API
- •Understanding Form Processing
- •Initializing the Process
- •Setting a Token
- •Setting an ID
- •Collecting All Possible Form Element Definitions
- •Looking for a Validation Function
- •Looking for a Submit Function
- •Allowing Modules to Alter the Form Before It’s Built
- •Building the Form
- •Allowing Functions to Alter the Form After It’s Built
- •Checking If the Form Has Been Submitted
- •Finding a Theme Function for the Form
- •Allowing Modules to Modify the Form Before It’s Rendered
- •Rendering the Form
- •Validating the Form
- •Token Validation
- •Built-In Validation
- •Element-Specific Validation
- •Validation Callbacks
- •Submitting the Form
- •Redirecting the User
- •Creating Basic Forms
- •Form Properties
- •Form IDs
- •Fieldsets
- •Theming Forms
- •Using #prefix, #suffix, and #markup
- •Using a Theme Function
- •Telling Drupal Which Theme Function to Use
- •Specifying Validation and Submission Functions with hook_forms()
- •Call Order of Theme, Validation, and Submission Functions
- •Writing a Validation Function
- •Form Rebuilding
- •Writing a Submit Function
- •Changing Forms with hook_form_alter()
- •Altering Any Form
- •Altering a Specific Form
- •Submitting Forms Programmatically with drupal_form_submit()
- •Dynamic Forms
- •Form API Properties
- •Properties for the Root of the Form
- •#action
- •#built
- •#method
- •Properties Added to All Elements
- •#description
- •#attributes
- •#required
- •#tree
- •Properties Allowed in All Elements
- •#type
- •#access
- •#after_build
- •#array_parents
- •#attached
- •#default_value
- •#disabled
- •#element_validate
- •#parents
- •#post_render
- •#prefix
- •#pre_render
- •#process
- •#states
- •#suffix
- •#theme
- •#theme_wrappers
- •#title
- •#tree
- •#weight
- •Form Elements
- •Text Field
- •Password
- •Password with Confirmation
- •Textarea
- •Select
- •Radio Buttons
- •Check Boxes
- •Value
- •Hidden
- •Date
- •Weight
- •File Upload
- •Fieldset
- •Submit
- •Button
- •Image Button
- •Markup
- •Item
- •#ajax Property
- •Summary
- •Filters
- •Filters and Text formats
- •Installing a Filter
- •Knowing When to Use Filters
- •Creating a Custom Filter
- •Implementing hook_filter_info()
- •The Process Function
- •Helper Function
- •Summary
- •Searching and Indexing Content
- •Building a Custom Search Page
- •The Default Search Form
- •The Advanced Search Form
- •Adding to the Search Form
- •Introducing the Search Hooks
- •Formatting Search Results with hook_search_page()
- •Making Path Aliases Searchable
- •Using the Search HTML Indexer
- •When to Use the Indexer
- •How the Indexer Works
- •Adding Metadata to Nodes: hook_node_update_index()
- •Indexing Content That Isn’t a Node: hook_update_index()
- •Summary
- •Working with Files
- •How Drupal Serves Files
- •Managed and Unmanaged Drupal APIs
- •Public Files
- •Private Files
- •PHP Settings
- •Media Handling
- •Upload Field
- •Video and Audio
- •File API
- •Database Schema
- •Common Tasks and Functions
- •Finding the Default Files URI
- •Copying and Moving Files
- •Checking Directories
- •Uploading Files
- •Getting the URL for a File
- •Finding Files in a Directory
- •Finding the Temp Directory
- •Neutralizing Dangerous Files
- •Checking Disk Space
- •Authentication Hooks for Downloading
- •Summary
- •Working with Taxonomy
- •The Structure of Taxonomy
- •Creating a Vocabulary
- •Creating Terms
- •Assigning a Vocabulary to a Content Type
- •Kinds of Taxonomy
- •Flat
- •Hierarchical
- •Multiple Hierarchical
- •Viewing Content by Term
- •Using AND and OR in URLs
- •Specifying Depth for Hierarchical Vocabularies
- •Automatic RSS Feeds
- •Storing Taxonomies
- •Module-Based Vocabularies
- •Creating a Module-Based Vocabulary
- •Keeping Informed of Vocabulary Changes with Taxonomy Hooks
- •Common Tasks
- •Displaying Taxonomy Terms Associated with a Node
- •Building Your Own Taxonomy Queries
- •Using taxonomy_select_nodes()
- •Taxonomy Functions
- •Retrieving Information About Vocabularies
- •taxonomy_vocabulary_load($vid)
- •taxonomy_get_vocabularies()
- •Adding, Modifying, and Deleting Vocabularies
- •taxonomy_vocabulary_save($vocabulary)
- •taxonomy_vocabulary_delete($vid)
- •Retrieving Information About Terms
- •taxonomy_load_term($tid)
- •taxonomy_get_term_by_name($name)
- •Adding, Modifying, and Deleting Terms
- •taxonomy_term_save($term)
- •taxonomy_term_delete($tid)
- •Retrieving Information About Term Hierarchy
- •taxonomy_get_parents($tid, $key)
- •taxonomy_get_parents_all($tid)
- •taxonomy_get_children($tid, $vid, $key)
- •taxonomy_get_tree($vid, $parent, $max_depth, $load_entities = FALSE)
- •Finding Nodes with Certain Terms
- •Additional Resources
- •Summary
- •Caching
- •Knowing When to Cache
- •How Caching Works
- •How Caching Is Used Within Drupal Core
- •Menu System
- •Caching Filtered Text
- •Administration Variables and Module Settings
- •Disabling Caching
- •Page Caching
- •Static Page Caching
- •Blocks
- •Using the Cache API
- •Caching Data with cache_set()
- •Retrieving Cached Data with cache_get() and cache_get_multiple()
- •Checking to See If Cache Is Empty with cache_is_empty()
- •Clearing Cache with cache_clear_all()
- •Summary
- •Sessions
- •What Are Sessions?
- •Usage
- •Session-Related Settings
- •In .htaccess
- •In settings.php
- •In bootstrap.inc
- •Requiring Cookies
- •Storage
- •Session Life Cycle
- •Session Conversations
- •First Visit
- •Second Visit
- •User with an Account
- •Common Tasks
- •Changing the Length of Time Before a Cookie Expires
- •Changing the Name of the Session
- •Storing Data in the Session
- •Summary
- •Using jQuery
- •What Is jQuery?
- •How jQuery Works
- •Using a CSS ID Selector
- •Using a CSS Class Selector
- •jQuery Within Drupal
- •Your First jQuery Code
- •Targeting an Element by ID
- •Method Chaining
- •Adding or Removing a Class
- •Wrapping Existing Elements
- •Changing Values of CSS Elements
- •Where to Put JavaScript
- •Adding JavaScript via a Theme .info File
- •A Module That Uses jQuery
- •Overridable JavaScript
- •Building a jQuery Voting Widget
- •Building the Module
- •Using Drupal.behaviors
- •Ways to Extend This Module
- •Compatibility
- •Next Steps
- •Summary
- •Localization and Translation
- •Enabling the Locale Module
- •User Interface Translation
- •Strings
- •Translating Strings with t()
- •Replacing Built-In Strings with Custom Strings
- •String Overrides in settings.php
- •Replacing Strings with the Locale Module
- •Exporting Your Translation
- •Starting a New Translation
- •Generating .pot Files with Translation Template Extractor
- •Creating a .pot File for Your Module
- •Using the Command Line
- •Using the Web-Based Extractor
- •Creating .pot Files for an Entire Site
- •Installing a Language Translation
- •Setting Up a Translation at Install Time
- •Installing a Translation on an Existing Site
- •Right-to-Left Language Support
- •Language Negotiation
- •Default
- •User-Preferred Language
- •The Global $language Object
- •Path Prefix Only
- •Path Prefix with Language Fallback
- •URL Only
- •Content Translation
- •Introducing the Content Translation Module
- •Multilingual Support
- •Multilingual Support with Translation
- •Localizationand Translation-Related Files
- •Additional Resources
- •Summary
- •What Is XML-RPC?
- •Prerequisites for XML-RPC
- •XML-RPC Clients
- •XML-RPC Client Example: Getting the Time
- •XML-RPC Client Example: Getting the Name of a State
- •Handling XML-RPC Client Errors
- •Network Errors
- •HTTP Errors
- •Call Syntax Errors
- •A Simple XML-RPC Server
- •Mapping Your Method with hook_xmlrpc()
- •Automatic Parameter Type Validation with hook_xmlrpc()
- •Built-In XML-RPC Methods
- •system.listMethods
- •system.methodSignature
- •system.methodHelp
- •system.getCapabilities
- •system.multiCall
- •Summary
- •Writing Secure Code
- •Handling User Input
- •Thinking About Data Types
- •Plain Text
- •HTML Text
- •Rich Text
- •Using check_plain() and t() to Sanitize Output
- •Using filter_xss() to Prevent Cross-Site Scripting Attacks
- •Using filter_xss_admin()
- •Handling URLs Securely
- •Making Queries Secure with db_query()
- •Keeping Private Data Private with hook_query_alter()
- •Dynamic Queries
- •Permissions and Page Callbacks
- •Cross-Site Request Forgeries (CSRF)
- •File Security
- •File Permissions
- •Protected Files
- •File Uploads
- •Filenames and Paths
- •Encoding Mail Headers
- •Files for Production Environments
- •SSL Support
- •Stand-Alone PHP
- •AJAX Security, a.k.a. Request Replay Attack
- •Form API Security
- •Protecting the Superuser Account
- •Summary
- •Development Best Practices
- •Coding Standards
- •Line Indention and Whitespace
- •Operators
- •Casting
- •Control Structures
- •Function Calls
- •Function Declarations
- •Function Names
- •Class Constructor Calls
- •Arrays
- •Quotes
- •String Concatenators
- •Comments
- •Documentation Examples
- •Documenting Constants
- •Documenting Functions
- •Documenting Hook Implementations
- •Including Code
- •PHP Code Tags
- •Semicolons
- •Example URLs
- •Naming Conventions
- •Checking Your Coding Style with Coder Module
- •Finding Your Way Around Code with grep
- •Summary
- •Optimizing Drupal
- •Caching Is the Key to Drupal Performance
- •Optimizing PHP
- •Setting PHP Opcode Cache File to /dev/zero
- •PHP Process Pool Settings
- •Tuning Apache
- •mod_expires
- •Moving Directives from .htaccess to httpd.conf
- •MPM Prefork vs. Apache MPM Worker
- •Balancing the Apache Pool Size
- •Decreasing Apache Timeout
- •Disabling Unused Apache Modules
- •Using Nginx Instead of Apache
- •Using Pressflow
- •Varnish
- •Normalizing incoming requests for better Varnish hits
- •Varnish: finding extraneous cookies
- •Boost
- •Boost vs. Varnish
- •Linux System Tuning for High Traffic Servers
- •Using Fast File Systems
- •Dedicated Servers vs. Virtual Servers
- •Avoiding Calling External Web Services
- •Decreasing Server Timeouts
- •Database Optimization
- •Enabling MySQL’s Query Cache
- •MySQL InnoDB Performance on Windows
- •Drupal Performance
- •Eliminating 404 Errors
- •Disabling Modules You’re Not Using
- •Drupal-Specific Optimizations
- •Page Caching
- •Bandwidth Optimization
- •Pruning the Sessions Table
- •Managing the Traffic of Authenticated Users
- •Logging to the Database
- •Logging to Syslog
- •Running cron
- •Architectures
- •Single Server
- •Separate Database Server
- •Separate Database Server and a Web Server Cluster
- •Load Balancing
- •File Uploads and Synchronization
- •Multiple Database Servers
- •Database Replication
- •Database Partitioning
- •Finding the Bottleneck
- •Web Server Running Out of CPU
- •Web Server Running Out of RAM
- •Identifying Expensive Database Queries
- •Identifying Expensive Pages
- •Identifying Expensive Code
- •Optimizing Tables
- •Caching Queries Manually
- •Changing the Table Type from MyISAM to InnoDB
- •Summary
- •Installation Profiles
- •Creating a New Installation Profile
- •The enhanced.info File
- •The enhanced.profile File
- •The enhanced.install File
- •Using hook_install_tasks and hook_install_tasks_alter
- •Summary
- •Testing
- •Setting Up the Test Environment
- •How Tests Are Defined
- •Test Functions
- •Test Assertions
- •Summary
- •Database Table Reference
- •Resources
- •Code
- •The Drupal Source Code Repository on GIT
- •Examples
- •Drupal API Reference
- •Security Advisories
- •Updating Modules
- •Updating Themes
- •Handbooks
- •Forums
- •Mailing Lists
- •Development
- •Themes
- •Translations
- •User Groups and Interest Groups
- •Internet Relay Chat
- •North America
- •Europe
- •Asia
- •Latin America / Caribbean
- •Oceania
- •Africa
- •Videocasts
- •Weblogs
- •Conferences
- •Contribute
- •Index
- •Numbers
CHAPTER 8 ■ WORKING WITH FIELDS
set the cardinality or number of values that can be created—our requirements call for only one value, whether there will be a “from” and “to” date, the granularity of the date and time, and the ability to override whether Drupal should covert the time entered when it is displayed based on various options. For the Event date, I’ll leave all of the values set to their default value and will save the field by clicking the “Save settings” button. I now have all of the required fields for the Event content type and
can begin authoring Events using the node creation form, as shown in Figure 8-7.
Figure 8-7. Creating a new Event
■ Note At the time the book was authored, the Date module was going through major rework due to changes to Drupal core. I suggest you check http://drupal.org/project/date for any updates to the approach or forms used to configure a date field.
Creating a Custom Field
Drupal 7 core comes with several generic field types that you can use for a wide variety of purposes. You can use the predefined field types to capture, store, and display values for a wide variety of purposes, but there may be instances where the standard field types (see Table 8-1) just don’t meet your needs. That’s
169
Download from Wow! eBook <www.wowebook.com>
CHAPTER 8 ■ WORKING WITH FIELDS
where the Field API comes into play, enabling the creation of custom field types that can be used in any content type created on your site.
Table 8-1. Standard Field Types in Drupal 7 Core
Field type |
Usage |
Boolean |
Used to collect true/false values using check boxes or radio buttons |
Decimal |
Used to collect numeric values that include a decimal point |
File |
Provides a file upload field that allows authors to attach a file to an instance of your |
|
content type |
Float |
Provides a text field for capturing numbers that contain decimal points |
Image |
Provides an image upload field that allows authors to attach images to an instance of |
|
your content type |
Integer |
Provides a text field that an author can enter an integer value into |
List |
Provides the ability to create a select list (drop-down or a list of values to select from) |
List (numeric) |
or check boxes/radio buttons that allow a user to select one or more values from a |
List (text) |
number of predefined values |
Long text |
Provides a multi-line text area that authors can enter information into (as opposed to a |
|
single line text box) |
Long text and |
Provides a multi-line text area and a multi-line summary area where an author can |
summary |
enter information |
Term |
Provides the ability to select a taxonomy term(s) |
reference |
|
Text |
A simple text box |
With the Field API, you have the ability to construct a custom field type for virtually any type of data input that you can think of. As an example, we will use the field type example from Drupal.org (http://api.drupal.org/api/drupal/developer--examples--color_example--color_example.module/7), which defines a custom field that renders text in a color specified in the field settings for that field type. We’ll use that field type to capture and display the color that event participants should wear when they attend an upcoming event.
The first step is to create a new directory named color_example in sites/all/modules/custom. In that directory, create a new file named color_example.info and place the following content into the
.info file.
170
CHAPTER 8 ■ WORKING WITH FIELDS
name = Color Example
description = "Creates a custom field for inputting and displaying text in a colorful fashion."
package = Pro Drupal Development core = 7.x
files[] = color_example.module php = 5.2
Next create another file named color_example.module and place the following content into that file.
<?php
/**
*@file
*An example field using the Field API.
*/
Save the files and enable the module. We are now ready to construct the details of the new RGB field type.
The first step is to call hook_field_info(), which defines the basic attributes of our new field. We define the field as color_example_rgb() and assign a label, description, default widget, and default formatter to the new field type.
/**
*Implements hook_field_info().
*Provides the description of the field.
*/
function color_example_field_info() { return array(
'color_example_rgb' => array( 'label' => t('Example Color RGB'),
'description' => t('Demonstrates a field composed of an RGB color.'), 'default_widget' => 'color_example_3text',
'default_formatter' => 'color_example_simple_text',
),
);
}
The next step is to define how the data collected in the field will be stored in the Drupal database. Prior to Drupal 7 and the Field API, we would have had to define the tables and schema ourselves in the modules that defined our content type and the custom fields within that content type. In Drupal 7 with the Field API, that task is handled for us through hook_field_schema(). For our example, we’ll store a seven-character field that represents the HTML hex color code that we want to use to render the text on the screen—for example, using #FF0000 renders the text in red. In the example here, we create a single column that stores the RGB value entered by the site administrator when he or she assigns the field to a content type.
171
CHAPTER 8 ■ WORKING WITH FIELDS
/**
* Implements hook_field_schema(). */
function color_example_field_schema($field) { $columns = array(
'rgb' => array('type' => 'varchar', 'length' => 7, 'not null' => FALSE),
);
$indexes = array(
'rgb' => array('rgb'),
);
return array(
'columns' => $columns, 'indexes' => $indexes,
);
}
The next step is to validate the user’s input by using hook_field_validate(). I’ll tell Drupal to validate that the user entered a value that matches a pattern of a typical HTML color code using preg_match(). I’ll check to see that the first character is a # and the following six characters are either a numeric digit or an alpha character that is between “a” and “f.” If the value entered doesn’t match that pattern, I’ll display an error.
/**
*Implements hook_field_validate().
*Verifies that the RGB field as combined is valid
*(6 hex digits with a # at the beginning).
*/
function color_example_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
foreach($items as $delta => $item) { if(!empty($item['rgb'])) {
if(! preg_match('@^#[0-9a-f]{6}$@', $item['rgb'])) { $errors[$field['field_name']][$langcode][$delta][] = array(
'error' => 'color_example_invalid',
'message' => t('Color must be in the HTML format #abcdef.'),
);
}
}
}
}
The next function defines what constitutes an empty field of this type. In this case, we use the PHP empty function to return either true or false depending on whether the field is empty.
/**
* Implements hook_field_is_empty(). */
function color_example_field_is_empty($item, $field) { return empty($item['rgb']);
}
172
CHAPTER 8 ■ WORKING WITH FIELDS
1.Field formatters are functions that define how the contents of a field are displayed. The hook_field_formatter_info() function identifies the types of formatters that are used to display the text and background in our example.
/**
* Implements hook_field_formatter_info(). */
function color_example_field_formatter_info() { return array(
//This formatter just displays the hex value in the color indicated. 'color_example_simple_text' => array(
'label' => t('Simple text-based formatter'), 'field types' => array('color_example_rgb'),
),
//This formatter changes the background color of the content region. 'color_example_color_background' => array(
'label' => t('Change the background of the output text'), 'field types' => array('color_example_rgb'),
),
);
}
Next I’ll build the renderable output for each of the two formatters just defined:
1.color_example_simple_text just outputs markup indicating the color that was entered and uses an inline style to set the text color to that value.
2.color_example_color_background does the same but also changes the background color of div.region-content.
/**
* Implements hook_field_formatter_view(). */
function color_example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
switch ($display['type']) {
// This formatter simply outputs the field as text and with a color. case 'color_example_simple_text':
foreach ($items as $delta => $item) {
$element[$delta]['#markup'] = '<p style="color: ' . $item['rgb']. '">'
. t('The color for this event is @code', array('@code' => $item['rgb']))
. '</p>';
}
break;
173
CHAPTER 8 ■ WORKING WITH FIELDS
//This formatter adds css to the page changing the '.region-content' area's
//background color. If there are many fields, the last one will win.
case 'color_example_color_background': foreach ($items as $delta => $item) {
drupal_add_css('div.region-content { background-color:' . $item['rgb']
.';}', array('type' => 'inline') ); $element[$delta]['#markup'] = '<p>'
. t('The color for this event has been changed to @code', array('@code' => $item['rgb'])) . '</p>';
}
break;
}
return $element;
}
The next set of functions defines the widget that will be used to display the field on the node edit form. For the RGB field, I’ll create three different types of widgets that the site administrator can select from.
1.A simple text-only widget where the user enters the “#ffffff”
2.A three–text field widget that gathers the red, green, and blue values separately
3.A farbtastic colorpicker widget that chooses the value graphically
I’ll use the hook_field_widget_info() function to define the three widgets.
/**
* Implements hook_field_widget_info(). */
function color_example_field_widget_info() { return array(
'color_example_text' => array(
'label' => t('RGB value as #ffffff'), 'field types' => array('color_example_rgb'),
),
'color_example_3text' => array( 'label' => t('RGB text fields'),
'field types' => array('color_example_rgb'),
),
'color_example_colorpicker' => array( 'label' => t('Color Picker'),
'field types' => array('color_example_rgb'),
),
);
}
174
CHAPTER 8 ■ WORKING WITH FIELDS
The hook_widget_form() function defines the actual structure of how the widgets will be displayed to the user. Three different forms are provided, for the three widget types.
1.color_example_text provides a text box to enter the HTML color code (e.g., #FFFFFF)
2.color_example_colorpicker – is essentially the same as color_example_text , but color_example_colorpicker adds a JavaScript colorpicker helper.
3.color_example_3text displays three text fields, one each for red, green, and blue. However, the field type defines a single text column, rgb, which needs an HTML color code. Define an element validate handler that converts our r, g, and b fields into a simulated single “rgb” form element.
/**
* Implements hook_field_widget_form(). */
function color_example_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$value = isset($items[$delta]['rgb']) ? $items[$delta]['rgb'] : ''; $element += array(
'#delta' => $delta,
);
$element['rgb'] = array();
switch ($instance['widget']['type']) {
case 'color_example_colorpicker': $element['rgb'] += array(
'#suffix' => '<div class="field-example-colorpicker"></div>', '#attributes' => array('class' => array('edit-field-example-
colorpicker')),
'#attached' => array(
//Add Farbtastic color picker. 'library' => array(
array('system', 'farbtastic'),
),
//Add javascript to trigger the colorpicker.
'js' => array(drupal_get_path('module', 'color_example') . '/color_example.js'),
),
);
//DELIBERATE fall-through: From here on the color_example_text and
//color_example_colorpicker are exactly the same.
case 'color_example_text': $element['rgb'] += array(
'#title' => t('Event\’s RGB Color'), '#type' => 'textfield', '#default_value' => $value,
//Allow a slightly larger size than the field length to allow for some
//configurations where all characters won't fit in input field. '#size' => 7,
175
CHAPTER 8 ■ WORKING WITH FIELDS
'#maxlength' => 7,
);
break;
case 'color_example_3text':
//Convert rgb value into r, g, and b for #default_value. if (isset($items[$delta]['rgb'])) {
preg_match_all('@..@', substr($items[$delta]['rgb'], 1), $match);
}
else {
$match = array(array());
}
//A fieldset to hold the three text fields.
$element += array( '#type' => 'fieldset',
'#element_validate' => array('color_example_3text_validate'),
//The following is set so that the validation function will be able
//to access external value information that otherwise would be
//unavailable.
'#delta' => $delta, '#attached' => array(
'css' => array(drupal_get_path('module', 'color_example') . '/color_example.css'),
),
);
// Create a textfield for saturation values for Red, Green, and Blue. foreach (array('r' => t('Red'), 'g' => t('Green'), 'b' => t('Blue')) as $key
=> $title) {
$element[$key] = array( '#type' => 'textfield', '#title' => $title, '#size' => 2,
'#default_value' => array_shift($match[0]), '#attributes' => array('class' => array('rgb-entry')),
// '#description' => t('The 2-digit hexadecimal representation of the @color saturation, like "a1" or "ff"', array('@color' => $title)),
);
}
break;
}
return $element;
}
The next function defines the validations that will be performed against the data entered by the user.
/**
*Validate the individual fields and then convert them into a single HTML RGB
*value as text.
176
CHAPTER 8 ■ WORKING WITH FIELDS
*/
function color_example_3text_validate($element, &$form_state) { $delta = $element['#delta'];
$field = $form_state['field'][$element['#field_name']][$element['#language']]['field']; $field_name = $field['field_name'];
if (isset($form_state['values'][$field_name][$element['#language']][$delta])) { $values = $form_state['values'][$field_name][$element['#language']][$delta]; foreach (array('r', 'g', 'b') as $colorfield) {
$val = hexdec($values[$colorfield]);
//If they left any empty, we'll set the value empty and quit. if (strlen($values[$colorfield]) == 0) {
form_set_value($element, array('rgb' => NULL), $form_state); return;
}
//If they gave us anything that's not hex, reject it.
if ( (strlen($values[$colorfield]) != 2) || $val < 0 || $val > 255) { form_error($element[$colorfield], t("Saturation value must be a 2-digit hexadecimal
value between 00 and ff."));
}
}
$value = sprintf('#%02s%02s%02s', $values['r'], $values['g'], $values['b']); form_set_value($element, array('rgb' => $value), $form_state);
}
}
And lastly I’ll use hook_field_error() to display an error message when the user enters something incorrectly.
/**
* Implements hook_field_error(). */
function color_example_field_widget_error($element, $error, $form, &$form_state) { switch ($error['error']) {
case 'color_example_invalid': form_error($element, $error['message']); break;
}
}
The next file to create is the JavaScript file that provides a farbtastic colorpicker for the fancier widget. Create another file in the module directory named color_example.js and include the following code:
/**
*@file
*Javascript for Color Example.
*/
177
CHAPTER 8 ■ WORKING WITH FIELDS
/**
* Provide a farbtastic colorpicker for the fancier widget. */
(function ($) { Drupal.behaviors.color_example_colorpicker = {
attach: function(context) { $(".edit-field-example-colorpicker").live("focus", function(event) {
var edit_field = this;
var picker = $(this).closest('tr').find(".field-example-colorpicker");
// Hide all color pickers except this one. $(".field-example-colorpicker").hide(); $(picker).show();
$.farbtastic(picker, function(color) { edit_field.value = color;
}).setColor(edit_field.value); });
}
}
})(jQuery);
The last file required for the color example module is the CSS file. Create a new file named color_example.css and include the following CSS:
/**
*@file
*CSS for Color Example.
*/
div.form-item table .form-type-textfield, div.form-item table .form-type-textfield * {
display: inline-block;
}
After saving the module, the field is ready to add to a content type. I’ll add the color field to Event by navigating to Structure -> Content Types and clicking the Manage Fields tabfor the Event content type as shown in Figure 8-8.
Figure 8-8. Adding the new Event Color field
178
CHAPTER 8 ■ WORKING WITH FIELDS
After clicking the Save button, I am taken to the next field settings page, which shows that there aren’t any field settings assigned to the Event Color field (e.g., maximum length). Click the “Save settings” button to display the overall settings page for the Event (see Figure 8-9). There on this form, I’ll enter the help text I want displayed below the field on the form and the default color value that will be used when the node edit form is displayed. I’ll click the “Save settings” button to finish the process of adding the field to the node edit form for Events.
Figure 8-9. Setting the configuration options for the new Event Color field
With the field added to the Event content type, I’m ready to test it out. Navigating to Add content -> Event reveals the new Event’s RGB Color field on the form with the default value (see Figure 8-10).
179
Download from Wow! eBook <www.wowebook.com>
CHAPTER 8 ■ WORKING WITH FIELDS
Figure 8-10. The new Event RGB Color field on the node edit form
After saving the Event, the new field is displayed formatted as defined in the module’s formatter functions. The image in Figure 8-11 displays the text in the color defined when the node was created, which in the example I created is red.
Figure 8-11. The new field is displayed in the color defined by the author.
So far I’ve shown you how to use the standard Drupal field types to create a new content type and how to create a field type that can be added to a content type. Next I’ll show you how to use the Field API to programmatically add fields using the Field API in a module.
180
