Skip to main content

Configure Cart Redirect in Sylius

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Sylius positions itself as an e-commerce framework, providing a high degree of flexibility and allowing for extensive customization of its features.

Sylius offers a range of customization options, extending beyond simply overriding existing classes and logic. The framework provides various configuration options, allowing you to tailor its behavior to your specific needs.

For instance, by default, Sylius redirects users to the cart overview page after they add an item to the cart. However, this can be easily customized.

If you prefer to redirect users back to the product page instead, you can achieve this by configuring the redirect option of the sylius_shop:product:add_to_cart_form Live component. This component is designed to handle custom routes and route parameters, making it straightforward to adapt to your requirements. By modifying the component's configuration, you can create a customized experience that meets your needs.

In our specific case, we want to change the configuration of the add_to_cart hookable which is configured for the sylius_shop.product.show.content.info.summary Twig hook.

Let's create a new file in config/packages/twig_hooks.yaml and add the following configuration:

'sylius_shop.product.show.content.info.summary':
add_to_cart:
component: 'sylius_shop:product:add_to_cart_form'
props:
routeName: 'sylius_shop_product_show'
routeParameters: {slug: '@=_context.product.getSlug()'}
product: '@=_context.product'
template: '@SyliusShop/product/show/content/info/summary/add_to_cart.html.twig'
priority: 100

Out of the box, the configuration for the sylius_shop:product:add_to_cart_form only includes the product and template properties. However, the component is also capable of accepting additional properties, specifically routeName and routeParameters. This flexibility allows us to reconfigure the component to meet our requirements without having to extend or modify the underlying code.

To achieve the desired redirect behavior, we can change the routeName property by passing in the name of the route we want to redirect to. In this case, we want to redirect the user back to the product page, so we can use the sylius_shop_product_show route. Since this route requires the product slug as a parameter, we can leverage the @=_context.product.getSlug() call to retrieve the slug of the currently viewed product and pass it as a route parameter.