Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
63
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 7 WORKING WITH NODES

Customizing the Node Form for Our Node Type

So far, you’ve got the metadata defined for your new node type and the access permissions defined. Next, you need to build the node form so that users can enter a job. You do that by implementing hook_form(). Drupal provides a standard node form that includes the title, body, and any optional fields that you have defined. For the job post content type, the standard form is more than adequate, so I’ll use it to render the add/edit form.

/**

* Implement hook_form() with the standard default form. */

function job_post_form($node, $form_state) { return node_content_form($node, $form_state);

}

Note If you are unfamiliar with the form API, see Chapter 11.

As the site administrator, if you’ve enabled your module, you can now navigate to Add content -> Job Post and view the newly created form (see Figure 7-3).

Figure 7-3. The form for submission of a job post

148

CHAPTER 7 WORKING WITH NODES

When you’re working with a node form and not a generic form, the node module handles validating and storing all the default fields it knows about within the node form (such as the title and body fields) and provides you, the developer, with hooks to validate and store your custom fields. We’ll cover those next.

Validating Fields with hook_validate()

When a node of your node type is submitted, your module will be called via hook_validate(). Thus, when the user submits the form to create or edit a job post, the invocation of hook_validate() will look for the function job_post_validate() so that you can validate the input in your custom field(s). You can make changes to the data after submission—see form_set_value(). Errors should be set with form_set_error(), as follows:

/**

* Implements hook_validate(). */

function job_post_validate($node) {

// Enforce a minimum character count of 2 on company names. if (isset($node->job_post_company) &&

strlen($node->job_post_company['und'][0]['value']) < 2) { form_set_error('job_post_company',

t('The company name is too short. It must be atleast 2

characters.'),

$limit_validation_errors = NULL);

}

}

Notice that you already defined a minimum word count for the body field in hook_node_info(), and Drupal will validate that for you automatically. However, the punchline field is an extra field you added to the node type form, so you are responsible for validating (and loading and saving) it.

Saving Our Data with hook_insert()

When a new node is saved, hook_insert() is called. This is the place to handle any custom processing of the node’s content before the node is saved. This hook is called only for the module that is defined in the node type metadata. This information is defined in the base key of hook_node_info() (see the “Providing Information About Our Node Type” section). For example, if the base key is job_post, then job_post_insert() is called. If you enabled the book module and created a new node of type book, job_post_insert() would not be called; book_insert() would be called instead because book.module defines its node type with a base key of book.

Note If you need to do something with a node of a different type when it’s inserted, use a node hook to hook into the general node submittal process. See the “Manipulating Nodes That Are Not Our Type with hook_node_insert()” section.

149

Download from Wow! eBook <www.wowebook.com>

CHAPTER 7 WORKING WITH NODES

Here’s the hook_insert() function for job_post.module. I’ll create a log entry in the watchdog table every time a new job posting node is created.

/**

* Implements hook_insert(). */

function job_post_insert($node) {

// log details of the job posting to watchdog

watchdog('job post', 'A new job post titled: '.$node->title.' for company: '. $node->job_post_company['und'][0]['value'].

' was added by UID: '.$node->uid, $variables = array(), WATCHDOG_NOTICE, $link = 'node/'.$node->nid);

}

Keeping Data Current with hook_update()

The update() hook is called when a node has been edited and the core node data has already been written to the database. This is the place to write database updates for related tables. Like hook_insert(), this hook is called only for the current node type. For example, if the node type’s module key in hook_node_info() is job_post, then job_post_update() is called.

/**

* Implements hook_update(). */

function job_post_update($node) {

// log details of the job posting to watchdog

watchdog('job post', 'A job post titled: '.$node->title.' for company: '. $node->job_post_company['und'][0]['value'].

' was updated by UID: '.$node->uid, $variables = array(), WATCHDOG_NOTICE, $link = 'node/'.$node->nid);

}

Cleaning Up with hook_delete()

Just after a node is deleted from the database, Drupal lets modules know what has happened via hook_delete(). This hook is typically used to delete related information from the database. This hook is called only for the current node type being deleted. If the node type’s base key in hook_node_info() is job_post, then job_post_delete() is called.

/**

* Implements hook_delete(). */

function job_post_delete($node) {

// log details of the job posting to watchdog

watchdog('job post', 'A job post titled: '.$node->title.' for company: '. $node->job_post_company['und'][0]['value'].

' was deleted by UID: '.$node->uid, $variables = array(), WATCHDOG_NOTICE, $link = 'node/'.$node->nid);

}

150

CHAPTER 7 WORKING WITH NODES

Modifying Nodes of Our Type with hook_load()

Another hook you need for your job_post module is the ability to add custom node attributes into the node object as it’s constructed. We need to inject the job post sponsor into the node loading process so it’s available to other modules and the theme layer. For that you use hook_load().

This hook is called just after the core node object has been built and is called only for the current node type being loaded. If the node type’s module key in hook_node_info() is job_post, then job_post_load() is called. In the example, I will insert a node attribute called sponsor and will assign a value that can then be used elsewhere.

/**

* Implements hook_load(). */

function job_post_load($nodes) {

//Add a new element to the node at load time for storing the

//job posting sponsor information

foreach ($nodes as $node) {

$node->sponsor = "ACME Career Services, Your Source for Drupal Jobs";

}

return $node;

}

Using hook_view()

Now you have a complete system to enter and edit job posts. However, your sponsors will be frustrated, because although sponsor information has been added previously through hook_load, you haven’t provided a way for the sponsor information to be displayed when viewing a job post. I’ll do that now with hook_view():

/**

* Implement hook_view(). */

function job_post_view($node, $view_mode) {

// Add and theme the sponsor so it appears when the job post is displayed if ($view_mode == 'full') {

$node->content['sponsor'] = array(

'#markup' => theme('sponsor', array('sponsor' => $node->sponsor, ‘sponsor_id’ => $node_nid)),

'#weight' => 100,

);

}

return $node;

}

I’ve broken the formatting of the sponsor into a separate theme function so that it can be easily overridden. This is a courtesy to the overworked system administrators who will be using your module but who want to customize the look and feel of the output. To enable this capability, I’ll create a hook_theme() function that defines how the module will handle theming the new sponsor field. In the hook_theme function, I’ll define the variables associated with the sponsor field and the template file that will be used to define how the sponsor information will be rendered as part of the node.

151

CHAPTER 7 WORKING WITH NODES

/**

* Implements hook_theme(). */

function job_post_theme() {

//define the variables and template associated with the sponsor field

//The sponsor will contain the name of the sponsor and the sponsor_id

//will be used to create a unique CSS ID

return array( 'sponsor' => array(

'variables' => array('sponsor' => NULL, 'sponsor_id' => NULL), 'template' => 'sponsor',

),

);

}

The last step in the process is to create the template file for displaying sponsor information. In the hook_theme() function, I assigned the value sponsor to the template file attribute—so I’ll need to create a sponsor.tpl.php file in my module directory. The content of that file is as follows:

<?php

/**

*@file

*Default theme implementation for rendering job post sponsor information

*Available variables:

*- $sponsor_id: the node ID asociated with the job posting

* - $sponsor: the name of the job post sponsor */ ?>

<div id="sponsor-<?php print $sponsor_id ?>" class="sponsor"> <div class="sponsor-title">

<h2>Sponsored by</h2> </div>

<div class="sponsored-by-message">

This job posting was sponsored by: <?php print $sponsor; ?> </div>

</div>

You will need to clear the cached theme registry so that Drupal will look at your theme hook. You can clear the cache using devel.module or by simply visiting the Modules page. You should now have a fully functioning job post entry and viewing system. Go ahead and enter some job posts and try things out. You should see your job post in a plain and simple format, as in Figures 7-4 and 7-5.

152

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]