blog-banner

Programmatically Create and Trigger Feeds Importer

  • Drupal 7
  • Drupal Planet
  • Feeds

We met with a challenging requirement where we needed to create a feed importer on node creation of a particular content type. It’s like for ‘n’ number of nodes there must be an ‘n’ number of feeds importer.

For that, I created a feed importer which will be considered as the template. Whenever the node of a specific content type is created, the template will be cloned and a new importer will be created.

The following code needs to reside in hook_node_insert() and will be used to clone the feeds importer:

// Pass the feed_importer_id which is already created
$template = feeds_importer('template');
// Get the exported code of already created feeds importer
$current_config = $template->config;
// Changed the name and description in configuration
$current_config['name'] = $node->title;
$current_config['description'] = $node->title;

// Start to create the new importer, argument will be a importer id for the new importer.
$new_importer = feeds_importer('ImporterId');
// Pass the configuration to the new importer.
$new_importer->setConfig($current_config);
foreach (array('fetcher', 'parser', 'processor') as $type) {
  $save->setPlugin($current_config->config[$type]['plugin_key']);
  $save->$type->setConfig($current_config->config[$type]['config']);
}
// Save the importer.
$new_importer->save();

The above code will create a new feed importer with the id ‘ImporterId’ on node creation.