How to programmatically alter feed item values before saving
-
06-02-2021 - |
题
Feeds Tamper does this job, which allows me to "tamper" with feed items' values before saving it to an entity.
My question is how can I do that programmatically in Drupal 8 with a custom module.
解决方案
Thanks to No Sssweat, I managed to use an EventSubscriber using afterParse
event to do this job.
File 1: mycustommodule/mycustommodule.services.yml
services:
mycustommodule.feeds_subscriber:
class: Drupal\mycustommodule\EventSubscriber\FeedsSubscriber
tags:
- {name: event_subscriber}
File 2: mycustommodule/src/EventSubscriber/FeedsSubscriber.php
<?php
namespace Drupal\mycustommodule\EventSubscriber;
use Drupal\feeds\Event\FeedsEvents;
use Drupal\feeds\Event\ParseEvent;
use Drupal\feeds\Feeds\Item\ItemInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Subscriber to Feeds events.
*
* This happens after parsing and before going
* into processing.
*/
class FeedsSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
return $events;
}
/**
* Acts on parser result.
*/
public function afterParse(ParseEvent $event) {
/** @var \Drupal\feeds\FeedInterface $feed */
$feed = $event->getFeed();
$feed_bundle_name = $feed->bundle();
// Only alter a particular feed
if ($feed_bundle_name == "MY_FEED_IMPORTER_MACHINE_NAME") {
/** @var \Drupal\feeds\Result\ParserResultInterface $result */
$result = $event->getParserResult();
for ($i = 0; $i < $result->count(); $i++) {
if (!$result->offsetExists($i)) {
break;
}
/** @var \Drupal\feeds\Feeds\Item\ItemInterface $item */
$item = $result->offsetGet($i);
/**
*
* My custom code here using $item->get() and $item->set()
* to alter whatever values I want.
*
*/
}
}
}
}
不隶属于 drupal.stackexchange