0

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?

1 Answer 1

0

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();
    };
  }
}
2
  • Thanks, that worked. I had to use hook entity insert, though, since I need node id to reference.
    – drupalhorn
    Oct 16, 2021 at 7:10
  • Glad it worked for you! Would you be kind enough to mark this as the accepted answer?
    – Beau
    Oct 17, 2021 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.