Search code examples
phpshopwareshopware6

How to get Custom Entity associated fields in Subscriber? 'Mapping definition neither have entities nor collection' error


I'm going to use Custom Entity associated fields in Subscriber. But I get this error: Mapping definition neither have entities nor collection.

Subscriber.php:

class Subscriber implements EventSubscriberInterface
{
    private EntityRepository $myfilter_property_group_option_tagRepository;

    public function __construct(EntityRepository $myfilter_property_group_option_tagRepository)
    {
        $this->myfilter_property_group_option_tagRepository = $myfilter_property_group_option_tagRepository;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ProductListingCriteriaEvent::class => [
                ['onListingCriteria', -200],
            ],
        ];
    }

    public function onListingCriteria(ProductListingCriteriaEvent $event): void
    {
        $context = $event->getContext();
        $optiontags = $this->myfilter_property_group_option_tagRepository->search(new Criteria(), $context);
        $event->getContext()->addExtension('optionTags', new ArrayEntity($optiontags));
        
        // Further 
        $event->getCriteria()->addAssociation('properties');
        $event->getCriteria()->addAssociation('properties.group');

        $criteria = $event->getCriteria();
        $filters = $criteria->getExtension('filters');

        if (!$filters instanceof FilterCollection) {
            return;
        }

        $propertyFilter = $filters->get('properties');
        // More

services.xml:

<service id="MyFilter\Subscriber\Subscriber">
    <tag name="kernel.event_subscriber"/>
    <argument type="service" id="myfilter_property_group_option_tag.repository"/>
</service>

Does someone know, what I'm doing wrong?

Also there is already an extension for this entity created in administration component. Is it possible to use that one?


Solution

  • myfilter_property_group_option_tag is based on a mapping definition, presumably mapping property_group_option and tag entities. Mappings themselves can't be fetched. Fetch the entities on either side of the mapping instead.

    $criteria = new Criteria();
    $criteria->addAssociation('myTags');
    
    $tags = new TagCollection();
    $options = $this->optionRepository->search($criteria, $context->getContext())->getEntities();
    /** @var PropertyGroupOptionEntity $option */
    foreach ($options as $option) {
        $extension = $option->getExtension('myTags');
        
        if (!$extension instanceof TagCollection) {
            continue;
        }
        
        $tags->merge($extension);
    }