How do I add a Shipping method to the saleschannel via the repository pattern

Hello,

I am making a shipping method plugin for the company I work for. We have an api that checks available shipping methods. The shipping method chosen by the customer needs to be added to the shopware database so that the shipping costs can be calculated.

 

Currently, I’m able to create shipping methods and add them to the database. They also show up in the backend, but they don’t show up in the sales channel. I can select them via the sales channel settings, and then they show up in the frontend.

 

Does anyone know how you can add the shipping method directly to sales channel?

 

Thanks in advance,

Koen

 

EDIT:  typo

public function assignNewShippingMethodToSalesChannels(): void
    {
        $context = Context::createDefaultContext();
        // Get the new shipping method entity by its ID
        $newShippingMethod = $this->shippingMethodRepository->search(
            (new Criteria([self::SHIPPING_METHOD_ID])),
            $context
        )->first();

        
        if (!$newShippingMethod) {
            return;
        }

        
        // Fetch all sales channels
        $criteria = new Criteria();
        $criteria->addAssociation('shippingMethods');

        $salesChannels = $this->salesChannelRepository->search($criteria, $context)->getEntities();

        // Prepare the data for updating sales channels
        $salesChannelData = [];
        foreach ($salesChannels as $salesChannel) {
            
            $shippingMethods = $salesChannel->getShippingMethods();
            
            $shippingMethods->add($newShippingMethod);
            $shippingMethodIds = [];
            foreach ($shippingMethods as $shippingMethod) {
                $shippingMethodIds[] = [ "id" => $shippingMethod->getId()];
            }
            
            $salesChannelData[] = [
                'id' => $salesChannel->getId(),
                'shippingMethods' => $shippingMethodIds,
            ];
        }
        // Update the sales channels
        
        $this->salesChannelRepository->update($salesChannelData, $context);
    }

Please give the above code a try and make sure to replace self::SHIPPING_METHOD_ID with your specific shipping method ID. I have personally tested this in version 6.5 and was successful.