November 28, 2012 - Comments Off on Drupal 7: Create Previous | Next links for nodes using CCK Date fields

Drupal 7: Create Previous | Next links for nodes using CCK Date fields

Recently we needed to implement a Next | Previous link feature for a site for two content types. For providing these links on a simple content type like a blog, the Flippy module may fit the bill. Flippy creates a themeable pager that gets its date from the node's 'created' date field. Blogs generally will benefit from this method of sorting and navigation, but what if your content type has a different, CCK, date field that you want to use for the links. The following code will take your CCK date field and use it to compare with same CCK date field of the current node:
[cce_php]
field_event_date['und'][0]['value']));
// Find the nid of the node with the timestamp just prior to $date
$prev_nid = db_query("SELECT n.nid FROM {node} n LEFT JOIN {field_data_field_event_date} f ON n.nid = f.entity_id WHERE type = 'event' AND UNIX_TIMESTAMP(f.field_event_date_value) < :posted ORDER BY field_event_date_value DESC LIMIT 1", array(':posted' => $date))->fetchField();
// Find the nid of the node with the timestamp just after $date
$next_nid = db_query("SELECT n.nid FROM {node} n LEFT JOIN {field_data_field_event_date} f ON n.nid = f.entity_id WHERE type = 'event' AND UNIX_TIMESTAMP(f.field_event_date_value) > :posted ORDER BY field_event_date_value ASC LIMIT 1", array(':posted' => $date))->fetchField();

if ($prev_nid > 0) {
$prev_link = l('Previous', "node/$prev_nid", array('html'=>TRUE, 'attributes' => array('title' => 'See Previous', 'class' => array('prev-link'))));
print($prev_link);
}

if ($next_nid > 0) {
$next_link = l('Next', "node/$next_nid", array('html'=>TRUE, 'attributes' => array('title' => 'See Previous', 'class' => array('next-link'))));
print(" | " . $next_link);
}
?>

[/cce_php]

The two db_query() calls in the code query the database for nodes based on their CCK Date field which is converted from a Mysql date (MM/DD/YY HH:MM:SS) to the unix epoch timestamp format for comparison. If there is a resulting nid, it is stored for output by drupal's l() function. The field we have is for an event and the field's name is 'field_date_event_value', seen in the SQL. You will have to dig into your content type to determine the exact name of the field you will use. Additionally you can see the syntax for the l() function for adding additional attributes to the generated link. The third argument takes a series of nested arrays that hold the 'title', 'class', 'id', etc.

This code could be extended to generate fuller pager with First, Last, Skip 5, or even Random links.

Links:

Published by: chazcheadle in The Programming Mechanism
Tags:

Comments are closed.