{"id":11988,"date":"2021-09-02T02:11:49","date_gmt":"2021-09-02T07:41:49","guid":{"rendered":"https:\/\/www.emizentech.com\/blog\/?p=11988"},"modified":"2023-01-30T11:03:40","modified_gmt":"2023-01-30T11:03:40","slug":"override-a-controller-in-shopware-6","status":"publish","type":"post","link":"https:\/\/multisitelocal.ezxdemo.com\/blog\/override-a-controller-in-shopware-6.html","title":{"rendered":"How To Override A Controller In Shopware 6"},"content":{"rendered":"<p>In Shopware 6, the controller is responsible for handling incoming requests, and it\u2019s the linchpin of Shopware 6 routing implementation.<\/p>\n<p>When you are working on the custom modules in Shopware 6, it\u2019s very crucial to override core module files instead of making changes to it right away. Overriding the controller in Shopware 6 provides the flexibility to change the core functionality according your Shopware 6 module development requirements.<\/p>\n<p>By following the steps given below you can override the core controller of Shopware 6 easily. <\/p>\n<p>Firstly,create a basic plugin in shopware using command:- .\/bin\/console plugin:create Emizentech<\/p>\n<p>Then create a plugin controller at this location:-Emizentech\/src\/Storefront\/Controller\/ProductController.php<br>\nand this following code:<\/p>\n<pre>&lt;?php declare(strict_types=1);\n\nnamespace Emizentech\\Storefront\\Controller;\n\nuse Shopware\\Storefront\\Controller\\StorefrontController;\nuse Shopware\\Core\\Content\\Product\\Exception\\ProductNotFoundException;\nuse Shopware\\Core\\Content\\Product\\SalesChannel\\Review\\AbstractProductReviewSaveRoute;\nuse Shopware\\Core\\Content\\Seo\\SeoUrlPlaceholderHandlerInterface;\nuse Shopware\\Core\\Framework\\Routing\\Annotation\\RouteScope;\nuse Shopware\\Core\\Framework\\Routing\\Annotation\\Since;\nuse Shopware\\Core\\System\\SalesChannel\\SalesChannelContext;\nuse Shopware\\Core\\System\\SystemConfig\\SystemConfigService;\nuse Shopware\\Storefront\\Framework\\Cache\\Annotation\\HttpCache;\nuse Shopware\\Storefront\\Framework\\Routing\\RequestTransformer;\nuse Shopware\\Storefront\\Page\\Product\\Configurator\\ProductCombinationFinder;\nuse Shopware\\Storefront\\Page\\Product\\ProductPageLoader;\nuse Shopware\\Storefront\\Page\\Product\\QuickView\\MinimalQuickViewPageLoader;\nuse Shopware\\Storefront\\Page\\Product\\Review\\ProductReviewLoader;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\EventListener\\AbstractSessionListener;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\n\n\/**\n * @RouteScope(scopes={\"storefront\"})\n *\/\nclass ProductController extends StorefrontController\n{\n    \/**\n     * @var ProductPageLoader\n     *\/\n    private $productPageLoader;\n\n    \/**\n     * @var ProductCombinationFinder\n     *\/\n    private $combinationFinder;\n\n    \/**\n     * @var MinimalQuickViewPageLoader\n     *\/\n    private $minimalQuickViewPageLoader;\n\n    \/**\n     * @var SeoUrlPlaceholderHandlerInterface\n     *\/\n    private $seoUrlPlaceholderHandler;\n\n    \/**\n     * @var ProductReviewLoader\n     *\/\n    private $productReviewLoader;\n\n    \/**\n     * @var SystemConfigService\n     *\/\n    private $systemConfigService;\n\n    private AbstractProductReviewSaveRoute $productReviewSaveRoute;\n\n    public function __construct(\n        ProductPageLoader $productPageLoader,\n        ProductCombinationFinder $combinationFinder,\n        MinimalQuickViewPageLoader $minimalQuickViewPageLoader,\n        AbstractProductReviewSaveRoute $productReviewSaveRoute,\n        SeoUrlPlaceholderHandlerInterface $seoUrlPlaceholderHandler,\n        ProductReviewLoader $productReviewLoader,\n        SystemConfigService $systemConfigService\n    ) {\n        $this-&gt;productPageLoader = $productPageLoader;\n        $this-&gt;combinationFinder = $combinationFinder;\n        $this-&gt;minimalQuickViewPageLoader = $minimalQuickViewPageLoader;\n        $this-&gt;seoUrlPlaceholderHandler = $seoUrlPlaceholderHandler;\n        $this-&gt;productReviewLoader = $productReviewLoader;\n        $this-&gt;systemConfigService = $systemConfigService;\n        $this-&gt;productReviewSaveRoute = $productReviewSaveRoute;\n    }\n\n  \/**\n     * @Since(\"6.0.0.0\")\n     * @HttpCache()\n     * @Route(\"\/detail\/{productId}\/switch\", name=\"frontend.detail.switch\", methods={\"GET\"}, defaults={\"XmlHttpRequest\": true})\n     *\/\n    public function switch(string $productId, Request $request, SalesChannelContext $salesChannelContext): JsonResponse\n    {\n        $switchedOption = $request-&gt;query-&gt;get('switched');\n\n        $options = $request-&gt;query-&gt;get('options');\n        $newOptions = $options !== null ? json_decode($options, true) : [];\n\n        try {\n            $redirect = $this-&gt;combinationFinder-&gt;find($productId, $switchedOption, $newOptions, $salesChannelContext);\n\n            $productId = $redirect-&gt;getVariantId();\n        } catch (ProductNotFoundException $productNotFoundException) {\n            \/\/nth\n        }\n\n        $host = $request-&gt;attributes-&gt;get(RequestTransformer::SALES_CHANNEL_ABSOLUTE_BASE_URL)\n            . $request-&gt;attributes-&gt;get(RequestTransformer::SALES_CHANNEL_BASE_URL);\n\n        $url = $this-&gt;seoUrlPlaceholderHandler-&gt;replace(\n            $this-&gt;seoUrlPlaceholderHandler-&gt;generate(\n                'frontend.detail.page',\n                ['productId' =&gt; $productId]\n            ),\n            $host,\n            $salesChannelContext\n        );\n\n        $response = new JsonResponse(['url' =&gt; $url,'productId' =&gt; $productId]);\n        $response-&gt;headers-&gt;set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, '1');\n\n        return $response;\n    }\n}\n<\/pre>\n<p>This class will override the vender Productcontroller class and method \u201cswitch\u201d .<\/p>\n<p>Next, we need to register our controller in the DI-container and make it public,<br>\nfor doing that create a new file in your plugin at location:- Emizentech\/src\/Resources\/config\/services.xml<br>\nand add the following code :-<\/p>\n<pre>&lt;?xml version=\"1.0\" ?&gt;\n\n&lt;container xmlns=\"http:\/\/symfony.com\/schema\/dic\/services\" \n           xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n           xsi:schemaLocation=\"http:\/\/symfony.com\/schema\/dic\/services http:\/\/symfony.com\/schema\/dic\/services\/services-1.0.xsd\"&gt;\n\n    &lt;services&gt;\n        &lt;service id=\"Emizentech\\Storefront\\Controller\\ProductController\" public=\"true\"&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Storefront\\Page\\Product\\ProductPageLoader\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Storefront\\Page\\Product\\Configurator\\ProductCombinationFinder\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Storefront\\Page\\Product\\QuickView\\MinimalQuickViewPageLoader\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Core\\Content\\Product\\SalesChannel\\Review\\ProductReviewSaveRoute\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Core\\Content\\Seo\\SeoUrlPlaceholderHandlerInterface\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Storefront\\Page\\Product\\Review\\ProductReviewLoader\"\/&gt;\n            &lt;argument type=\"service\" id=\"Shopware\\Core\\System\\SystemConfig\\SystemConfigService\" \/&gt;\n            &lt;call method=\"setContainer\"&gt;\n                &lt;argument type=\"service\" id=\"service_container\"\/&gt;\n            &lt;\/call&gt;\n        &lt;\/service&gt;\n    &lt;\/services&gt;\n&lt;\/container&gt;\n<\/pre>\n<p>Please also note the call tag, which is necessary in order to set the DI container to the controller.<\/p>\n<p>Once we\u2018ve registered our new controller, we have to tell Shopware how we want it to search for new routes in our plugin. This is done with a routes.xml file at :Emizentech\/src\/Resources\/config\/ location and add the following code:-<\/p>\n<pre>&lt;routes xmlns=\"http:\/\/symfony.com\/schema\/routing\"\n        xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n        xsi:schemaLocation=\"http:\/\/symfony.com\/schema\/routing\n        https:\/\/symfony.com\/schema\/routing\/routing-1.0.xsd\"&gt;\n\n    &lt;import resource=\"..\/..\/Storefront\/Controller\/**\/*ProductController.php\" type=\"annotation\" \/&gt;\n&lt;\/routes&gt;\n<\/pre>\n<p>That\u2019s it now the switch method of product controller is overridden and also we can also make a new controller with this process<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>In Shopware 6, the controller is responsible for handling incoming requests, and it\u2019s the linchpin of Shopware 6 routing implementation. When you are working on the custom modules in Shopware 6, it\u2019s very crucial to override core module files instead of making changes to it right away. Overriding the controller in Shopware 6 provides the<\/p>\n","protected":false},"author":36,"featured_media":12334,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"MSN_Categories":"Uncategorized","MSN_Publish_Option":false,"MSN_Is_Local_News":false,"MSN_Is_AIAC_Included":"Empty","MSN_Location":"[]","MSN_Add_Feature_Img_On_Top_Of_Post":false,"MSN_Has_Custom_Author":false,"MSN_Custom_Author":"","MSN_Has_Custom_Canonical_Url":false,"MSN_Custom_Canonical_Url":"","_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[85],"tags":[84],"class_list":{"0":"post-11988","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-shopware","8":"tag-shopware"},"modified_by":"Marketing EmizenTech","featured_image_src":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/How-To-Override-A-Controller-In-Shopware-6-1.png","featured_image_src_square":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/How-To-Override-A-Controller-In-Shopware-6-1.png","author_info":{"display_name":"Vivek Khatri","author_link":"https:\/\/multisitelocal.ezxdemo.com\/blog\/author\/vivek"},"_links":{"self":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts\/11988","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/users\/36"}],"replies":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/comments?post=11988"}],"version-history":[{"count":0,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts\/11988\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/media\/12334"}],"wp:attachment":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/media?parent=11988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/categories?post=11988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/tags?post=11988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}