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
         $message = 'error';
         $message = 'success';
  • 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

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


    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
    ) {
        $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);

        return $resultRedirect;
  • 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? 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/… 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.