Search code examples
shopware

custom validate in shopware shipping address in confirm order page


How to add my custom validate in shopware shipping address in confirm order page .once if success that process to confirm order. Please explain how to do this.


Solution

  • Can't you just add additional field to address while address creation?

    public static function getSubscribedEvents()
    {
        return array(
            'Shopware_Form_Builder' => ['onFormBuild', 1000]
        );
    }
    
    public function onFormBuild(\Enlight_Event_EventArgs $event)
    {
        if (
            (   $event->getReference() !== \Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType::class &&
                $event->getReference() !== \Shopware\Bundle\AccountBundle\Form\Account\AddressFormType::class  )
        ) {
            return;
        }
    
        /** @var \Symfony\Component\Form\Form $builder */
        $builder = $event->getBuilder();
    
        $builder->get('additional')
            ->add('yourFieldName', \Symfony\Component\Form\Extension\Core\Type\TextType::class, [
                'constraints' => [
                    new NotBlank()
                ]
            ]);
    }
    

    If no, then you should subscribe to checkout postdispatch and check what you want:

    public static function getSubscribedEvents()
    {
        return array(
            'Enlight_Controller_Action_PreDispatch_Frontend_Checkout' => 'onFrontendPreDispatchCheckout',
        );
    }
    
    /**
     * @param \Enlight_Controller_ActionEventArgs $args
     */
    public function onFrontendPreDispatchCheckout(\Enlight_Controller_ActionEventArgs $args)
    {
        /**@var $subject \Shopware_Controllers_Frontend_Checkout */
        $subject = $args->getSubject();
        $request = $subject->Request();
        $response = $subject->Response();
        $action = $request->getActionName();
        $view = $subject->View();
    
        if (!$request->isDispatched() || $response->isException() || 
        // only in case action is payment or confirm we should chcek it
        ($action != 'payment' && $action != 'confirm') ||
        !$view->hasTemplate()
        ) {
            return;
        }
    
        $validation = $this->thereWeCheckIt();
        if (
            $validation['message']
        ) {
                    $subject->forward('index', 'account', 'frontend', array(
                        'errorVariable' => $validation['message'],
                    ));
        }
    }
    

    Then you need also postDispatch account controller and show errorVariable to customer.