Shopware: cancel the addition of product to the cart conditionally

Viewed 60

I'd like to implement a feature that makes an external API call then depending on whether the request is fulfilled the product line-item gets added to the cart else it shows a translated flash message to the customer that the product couldn't be added to the cart for X reason/s.

What I have tried is subscribing to the BeforeLineItemAddedEvent but it seems that the line item is already added to the cart by this point and I'm not quite sure how to implement the flash message thing.

1 Answers

You can implement your own custom cart validator. If your validation criteria is based on a request to an external resource, be mindful that this validator will be called every time the cart gets built. Maybe consider caching those requests.

Service definition:

<service id="MyPlugin\Core\Checkout\Cart\LineItem\CustomValidator">
    <tag name="shopware.cart.validator"/>
</service>

Validator class:

class CustomValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
    {
        foreach ($cart->getLineItems()->getFlat() as $lineItem) {
            // your custom logic here
            if ($lineItem->getLabel() === 'Aerodynamic Concrete Isoswitch') {
                $errors->add(new IncompleteLineItemError($lineItem->getId(), 'yourCustomSnippet'));
                $cart->getLineItems()->removeElement($lineItem);
            }
        }
    }
}

You might want to implement your own custom extension of Error instead using the pre-existing IncompleteLineItemError here.

Your translated messages json:

{
  // storefront.en-GB.json
  "checkout": {
    "yourCustomSnippet": "This is not allowed"
  }
}

You can find a more detailed explanation in the docs.

Related