Score:0

Auto create a feed when a node is added

ro flag

I am looking for a way to automatically add a feed (of a specific feed type), whenever a node is added (for a specific content type) using the node fields to auto-create the feed.

I have searched this site and globally; the closest solution I could find is the one described in Programmatically create and trigger feeds importer, for Drupal 7, although I cannot see why a template should be needed.

I think I should be able to do this in a custom module, but I am a bit stuck.

Does anyone know how this could be done in Drupal 8?

Score:0
in flag

I think the solution for you is hook_ENTITY_TYPE_update(). Below is a simplified code sample; as always, use dependency injection and other best practices in your production code.

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function mymodule_node_update(\Drupal\node\Entity\Node $node) {
  if ($node->bundle() === 'my_content_type') {
    $feed = \Drupal\feeds\Entity\Feed::create([
      // Name the new Feed after the node; or anything you want!
      'title' => "{$node->label()} importer",

      // Assign the ID of the Feed Type to use for generating this Feed.
      'type' => $feed_type_id,

      // This will vary depending on the type of importer.
      'source' => 'https://www.example.com/data.csv',

      // Optionally, set uid to 1 to always belong to the Drupal superuser.
      'uid' => \Drupal::currentUser()->id(),
    ]);
    // Kick off the import after successfully saving the Feed. 
    if (in_array($feed->save(), [SAVED_NEW, SAVED_UPDATED], TRUE)) {
      $feed->import();
    };
  }
}
drupalhorn avatar
ro flag
Thanks, that worked. I had to use hook entity insert, though, since I need node id to reference.
in flag
Glad it worked for you! Would you be kind enough to mark this as the accepted answer?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.