Search code examples
eventsshopware

How to add an Action to Account Controller in Shopware


How to add a custom action to an existing Controller in Shopware?

Examples (url structure):

/account/bonus
/account/custom
/account/...

Usually it's easier and cleaner to create a new controller for that purpose, but in some cases it's necessary.


Solution

  • Spoiler: Replace the controller

    There is no cleaner way than to replace the whole controller and extend it's functionality, so it's nearly as clean as Shopware's hooks.

    Guide

    Add a new Subscriber to your Plugin

    class AccountSubscriber implements SubscriberInterface
    {
        /**
         * @return array
         */
        public static function getSubscribedEvents()
        {
            return array(
                'Enlight_Controller_Dispatcher_ControllerPath_Frontend_Account' => 'getAccountController'
            );
        }
    
        /**
         * @return string
         */
        public function getAccountController()
        {
            return $this->getPath() . '/Controllers/Frontend/AccountExtended.php';
        }
    
        /**
         * @return string
         */
        public function getPath()
        {
            $plugin = Shopware()->Container()->get('kernel')->getPlugins()['AcmeYourPlugin'];
    
            return $plugin->getPath();
    
        }
    }
    

    Downsides

    Unfortunately some controller have private methods which impact the logic. Like the Account Controller. So it's not always possible to simply extend the controller.

    In the end, try to add a new controller with a new route. It's easier, and cleaner.