Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created February 29, 2012 08:46
Show Gist options
  • Save thsutton/1939238 to your computer and use it in GitHub Desktop.
Save thsutton/1939238 to your computer and use it in GitHub Desktop.
Basic Feeds support for nodereference CCK fields.

Node Reference support for Feeds

Adding basic support for Node Reference fields to the Feeds module is pretty straightforward (if you don't worry too much about the advanced features of nodereference).

In fact, it's almost a direct copy of the existing support for basic CCK field types. Just check for a different field type (line 19) and lookup the nid based on the GUID from the feed (line 51).

I've used a CSV file with a quoted, comma-separated field containing GUIDs of my target nodes and explode the value using Feeds Tamper.

To "install" this code, just drop nodereference.inc into the feeds/mappers/ directory and clear your Drupal cache.

<?php
/**
* @file
* On behalf implementation of Feeds mapping API for content.module (CCK).
*/
/**
* Implementation of hook_feeds_node_processor_targets_alter().
*
* @see FeedsNodeProcessor::getMappingTargets().
*/
function nodereference_feeds_node_processor_targets_alter(&$targets, $content_type) {
$info = content_types($content_type);
$fields = array();
if (isset($info['fields']) && count($info['fields'])) {
foreach ($info['fields'] as $field_name => $field) {
if ('nodereference' == $field['type']) {
$fields[$field_name] = isset($field['widget']['label']) ? $field['widget']['label'] : $field_name;
}
}
}
foreach ($fields as $k => $name) {
$targets[$k] = array(
'name' => check_plain($name),
'callback' => 'nodereference_feeds_set_target',
'description' => t('The CCK @name field of the node.', array('@name' => $name)),
);
}
}
/**
* Callback for mapping. Here is where the actual mapping happens.
*
* When the callback is invoked, $target contains the name of the field the
* user has decided to map to and $value contains the value of the feed item
* element the user has picked as a source.
*/
function nodereference_feeds_set_target($node, $target, $value) {
$field = isset($node->$target) ? $node->$target : array();
if (! is_array($value)) {
$value = array($value);
}
// Handle multiple value fields.
$i = 0;
foreach ($value as $v) {
$v = db_fetch_array(db_query("SELECT nid FROM {feeds_node_item} WHERE guid = '%s'", $v));
if ($v) {
$field[$i] = $v;
$i++;
}
}
$node->$target = $field;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment