0

I have a submission form and a controller, with the execute method. At the moment, after sending the form, my page reloads and on top of the page I get an alert that notifies the user about the success or failure of the operation, how can I instead redirect to a custom success page?

The execute method of my controller app/code/Vendor/Module/Controller/Order/Create.php:

    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        $sampleIds = explode(',', $data['sample_ids']);
        if (count($sampleIds) >  $this->helper->getMaxCount()) {
            $this->messageManager->addError(__('The count of "samples" exceeds the limit'));
            $data = null;
        }

        if ($data) {
            /** @var \Vendor\Module\Model\Order $model */
            $model = $this->_objectManager->create('Vendor\Module\Model\Order');
            $model->setData($data);
            $model->setStoreId($this->_storeManager->getStore()->getId());

            try {
                $this->objectRepository->save($model);
                $this->messageManager->addSuccess(__('Request was added to processing.'));
                $this->dataPersistor->clear('vendor_sample_order');

                // Send email
                $this->helper->sendEmail($model);

            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
            }
        }
        return $resultRedirect->setRefererOrBaseUrl();
    }
2

You can use the below code in your custom controller in execute method to redirect on any pages.

public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('routename/controllerpath/controllername');
return $resultRedirect;
}

No need to declare $this->resultRedirectFactory in the construct as its auto declared in the construct of \Magento\Framework\App\Action\Action to which your custom controller should extend. Otherwise, you'll get an error during compilation: resultRedirectFactory is already declared

Hope this helps.

0

Try this code

$this->_redirect("your/url/here");
0

You can try this code

return $resultRedirect->setPath('your_path');
0

Try this:

 $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('yourpath');
    return $resultRedirect;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.