1

I have a form that post data to controller in Magento 2 Frontend, i want to do some validation, and redirect back to previous page after validation with success or error message, here's how i redirect back to previous page:

public function execute()
    {
        // Do Validation
        if(empty($input))
         $message = 'error';
        else
         $message = 'success';
        $this->_redirect($this->_redirect->getRefererUrl());
    }
  • If my answer worked could you accept my answer , but if it didn't work then tell me whats wrong. – klict Feb 1 '17 at 14:11
2

You can show your error/success message with ManagerInterface. Here is an example to show you how you can use it.

  <?php


    use Magento\Backend\App\Action\Context;
    use \Magento\Framework\Controller\ResultFactory;

class ClassName extends \Magento\Framework\App\Action\Action
{

    protected $_messageManager;

    public function __construct(
        Context $context,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        parent::__construct($context);
        $this->_messageManager = $messageManager;
    }

    public function execute()
    {
        // Do Validation
        if (empty($input)) {
            $this->_messageManager->addErrorMessage('Your Error Message');
        } else {
            $this->_messageManager->addSuccessMessage('Your Success Message');
        }
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());

        return $resultRedirect;
    }
}
| improve this answer | |
  • can i set multiple error message? – simple guy Feb 1 '17 at 9:24
  • Yes, just call addErrorMessage method. – klict Feb 1 '17 at 10:03
  • How can I return my collection from controller to the previous page? – Vinod Kumar Aug 29 '17 at 6:10
  • 1
    Hi @Vinodkumar, if you wish to get an answer then it's better to create your own question. A comment is not best way to get an answer. – klict Aug 30 '17 at 9:35
  • I had created my own question but there is no response till now: magento.stackexchange.com/questions/190971/… – Vinod Kumar Aug 30 '17 at 9:53

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.