Drupal: Not node queue - node reference

billk2's picture

I thought I'd better share this. Mainly so I don't forget, but also for anyone else who may have this strangely specific need.

Problem: An editor wants to control the ordering of a list of new content that's featured in an email newsletter.

Not happy that they can now automatically generate an HTML page featuring stories from the last 24 hours with the output formatted into the table layout needed for pasting into an email, there's one little extra request. With their old CMS they had to edit the time of each article in order to control the ordering of the items - the important stuff needed to be at the top of the email. Can you make it so I can reorder them easily?

Flag them as sticky? No wait - ha! No problem. That's what nodequeue does, right? Unfortunately not. Nodequeue's great for editors because they can happily reorder their items, but there's no simple way to automatically populate those queues.

So what's the answer? Calling CCK node_reference, we need your help. My experience with it's been simply using node_reference to link one node with another. Which isn't surprising, as that's what it's designed to do. But when you create a new node reference CCK field, there's a often overlooked option - the default value. But what's even more powerful is the fact you can use PHP to calculate it.

Great, so you can get it to choose today's date or something? Well, yes - but what about using a view? Now it's getting interesting.

So here's what we did. We created a view that filtered the appropriate content and pasted the following code into the default value PHP box on the node_reference field setting:

<?php
// get our 'newsletter_items' view
$view = views_get_view('newsletter_items');
$view->set_items_per_page(60);
$view->render();
$res = $view->result;

// make an array of node ids
$result = array();
foreach ($res as $arr) {
$results[] = array('nid' => $arr->nid);
}

return $results;
?>

So now the editor creates a new Newsletter node (with our node reference field), and it's automatically populated with our view's nodes. Then they can rearrange, add, edit and delete them to their hearts content. Because we're using the autocomplete text field widget, it's all drag and drop.

Job done.

Back to top