Overriding Attribute Value
Event
See Event Pre-Update-Attribute-Value
Event Subscriber
In certain cases, for example if instead of an internal identifier (e.g., 1) a readable label (e.g., red) should be used, it is possible to modify the value within an event. This is done through an event subscriber that intervenes before saving the attribute value and replaces the value if needed.
Example
<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Twocream\ProductAttributeBundle\Event\TwocreamProductAttributeEvents;
use Twocream\ProductAttributeBundle\Event\UpdateAttributeValueEvent;
class TwocreamProductAttributeListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
TwocreamProductAttributeEvents::PRE_UPDATE_ATTRIBUTE_VALUE => 'preUpdateAttributeValue'
];
}
public function preUpdateAttributeValue(UpdateAttributeValueEvent $event): void
{
$attributeValueData = $event->getAttributeValueData();
if (
!empty($attributeValueData['data']['fieldName'])
&& $attributeValueData['data']['fieldName'] == 'SAP_COLOR'
) {
$colors = [
1 => 'red',
45 => 'yellow',
132 => 'green'
];
$sapValue = $attributeValueData['data']['value'];
$attributeValueData['data']['value'] = $colors[$sapValue] ?? $sapValue;
}
$event->setAttributeValueData($attributeValueData);
}
}