0
votes

I have built a custom subscriber in my plugin for Shopware 6 that subscribes to

\Shopware\Core\Content\Product\ProductEvents::PRODUCT_WRITTEN_EVENT = 'product.written';

public function onProductWrittenEntity(EntityWrittenEvent $event): void
{
        //$event->getContext() is returning the Shopware\Core\Framework\Context
}

I want to get domain URL of this current salesChannel having those productIds which are currently written. how can i do that?

3

3 Answers

2
votes

When you edit the products over the API or inside the administration, you are in a "admin context", that means no sales-channel is available. This is because your changes are globally and you are not limited to a specific sales-channel.

The SalesChannelContext is only available if the action that was triggered originated in the storefront or came over the store-api.

Long story short: You can't access the salesChannelContext from the EntityWrittenEvent, as most of the times there is no specific SalesChannel, where the event was triggered.

Maybe you can explain your use case a little bit more, so we can suggest alternatives.

2
votes

You can obtain the salesChannelId by running the following code:

$event->getContext()->getSource()->getSalesChannelId()

With that salesChannelId and inserting the SalesChannelRepository via the services.xml into your Subscriber, you can load the required information from that sales-channel.

1
votes

in case someone run in this Problem: You can for example Subscribe to the Event "SalesChannelContextResolvedEvent". Store all the Data in a variable as type array (Argument2 from the construct, "$this->saleschannelContext"). And call it in where ever you need it, for example an other event (you can call it so -> "$this->salechannelContext").

 public function __construct(EntityRepository $discountExtensionRepository){
    $this->discountExtensionRepository = $discountExtensionRepository;
    $this->salechannelContext = array();
}

public static function getSubscribedEvents(): array{
    return [
        SalesChannelContextResolvedEvent::class => "onPageLoaded",
        ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded'
        
    ];
}
public function onPageLoaded(SalesChannelContextResolvedEvent $event){
    $this->salechannelContext = $event->getSaleschannelContext();
}
public function onProductsLoaded(EntityLoadedEvent $event):void{
     dump($this->salechannelContext);
}

Probably not the best practice way because i guess there is a way to get it directly from die Product event, but it is one way of manys.

[EDIT]: You can get all Storefront and Product informations with this event.

use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
 public static function getSubscribedEvents(): array{
    return [
        'sales_channel.product.loaded' => 'onSalesChannelLoaded'
        
    ];
}
public function onSalesChannelLoaded(SalesChannelEntityLoadedEvent $event):void{