cancel
Showing results for 
Search instead for 
Did you mean: 

Error/Success message not showing on one page in custom module

SOLVED

Error/Success message not showing on one page in custom module

In my custom module I have two pages, an index and a addProduct page. On the index page error/success messages show without a problem. On the addProduct page neither error nor success message show. The div for the message is there, but it is empty. I have compared it with everything on the index page, but have not found the problem yet. Can you please see, if you can find it? What am I overlooking? I've spent hours trying to find the problem.

 

Here is my controller:

<?php

namespace [Vendor]\[Module]\Controller\Index;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Element\Messages;

class Saveproduct extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_session;
	
	/**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    protected $_resultRedirectFactory;
   
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;
   
     /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $_messageManager;
    
    /**
     * @var \Magento\Framework\Data\Form\FormKey\Validator
     */
    protected $_formKeyValidator;
 
    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param  \[Vendor]\[Modulename]\Model\CustomProductFactory $customproductFactory
     * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
     */

    public function __construct(Context $context, 
           \Magento\Customer\Model\Session $customerSession,
           \Magento\Framework\View\Result\PageFactory $resultPageFactory, 
           \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
           \Magento\Framework\Message\ManagerInterface $messageManager,
           \[Vendor]\[Modulename]\Model\CustomProductFactory $customproductFactory, 
           \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator)
    {
        parent::__construct($context);

        $this->_session = $customerSession;
        $this->_resultRedirectFactory = $resultRedirectFactory;
        $this->_resultPageFactory = $resultPageFactory;
        $this->_messageManager = $messageManager;
        $this->customproductFactory = $customproductFactory;   
        $this->_formKeyValidator = $formKeyValidator;

    }

    /**
     * Save action
     *
     * @return void
     */
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();

        $data = $this->getRequest()->getPostValue();

        try{

            $om = \Magento\Framework\App\ObjectManager::getInstance();
            $customerSession = $om->create('Magento\Customer\Model\Session');
           
           //Validation
           $error = false;
         
           if ((!isset($data['description'])) || (!\Zend_Validate::is(trim($data['description']), 'NotEmpty'))) {
                $error = true;
            }
         
		 if ($error) {
                throw new \Exception('Missing required field');
            }

           // Save to database
           $customproduct->setData($data);
          
           if( $customproduct
               $this->_messageManager->addSuccess(__('Your Custom order has been saved.'));
           } else {
               throw new \Exception('Custom order did not get saved!');
           }
  
           return $this->_redirect('[modulename]/index/index');

        }catch (\Exception $e){
           $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e->getMessage());
           $this->_messageManager->addError(__('We were unable to submit your request. Please try again!'));

           return $this->_redirect('[modulename]/index/addproduct'); } } }

Here is the theme app/design/frontend/Mgs/luxury/Magento_Theme/templates/messages.phtml - and this does show up in the inspector:

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<div data-bind="scope: 'messages'">
    <div data-bind="foreach: { data: cookieMessages, as: 'message' }" class="messages">
        <div data-bind="attr: {
            class: 'message-' + message.type + ' ' + message.type + ' message',
            'data-ui-id': 'message-' + message.type
        }">
            <div data-bind="html: message.text"></div>
        </div>
    </div>
<div data-bind="scope: 'messages'">
    <div data-bind="foreach: { data: messages().messages, as: 'message' }" class="messages">
        <div data-bind="attr: {
            class: 'message-' + message.type + ' ' + message.type + ' message',
            'data-ui-id': 'message-' + message.type
        }">
            <div data-bind="html: message.text"></div>
        </div>
    </div>
</div>
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                        "messages": {
                            "component": "Magento_Theme/js/view/messages"
                        }
                    }
                }
            }
    }
</script>

Here is the addProduct xml file:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="2columns-left">
 <update handle="customer_account"/>
   <body>
        <referenceContainer name="columns.top">
            <block class="Magento\Theme\Block\Html\Title" name="page.main.title" template="html/title.phtml"/>
            <container name="page.messages" htmlTag="div" htmlClass="page messages">
                <block class="Magento\Framework\View\Element\Template" name="ajax.message.placeholder" template="Magento_Theme::html/messages.phtml"/>
                <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
            </container>
        </referenceContainer>
        <referenceContainer name="content">
            <block type="core/template" class="[Vendor]\[ModuleName]\Block\Customproduct" name="mymeasurements_index_addproduct.view" after="div.sidebar-main" template="Vendor_ModuleName::customproduct.phtml" cacheable="false" />
        </referenceContainer>
    </body>
</page>

and here is the block:

<?php
namespace [Vendor]\[ModuleName]\Block;

class Customproduct extends \Magento\Framework\View\Element\Template
{
    public $_storeManager;
    public $_customerSession;
    public $_session;
    public $customproduct;
    public $_context;

    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\Session $session,
        \[Vendor]\[ModuleName]\Model\CustomProductFactory $customproductFactory 
    )
    {
        parent::__construct($context);

        $this->customproductFactory = $customproductFactory;
        $this->_storeManager = $storeManager;
        $this->_session = $session;
        $this->_context = $context;
    }

    function _prepareLayout()
    {
        if($this->_session->isLoggedIn()){

            $value = $this->getRequest()->getParam('id');
            if ($value) {
                $this->customproduct = $this->customproductFactory->create();
                $this->customproduct->setId($value);
                $this->customproduct = $this->customproduct->load($value);
            }
        }
        $this->pageConfig->getTitle()->set(__('Add custom product'));

        return parent::_prepareLayout();
    }
   function getSession(){
        return $this->_session;
    }
}

Thank you for taking a look!

3 REPLIES

Re: Error/Success message not showing on one page in custom module

Both the index and the addProduct pages are in MyAccount, if that has anything to do with it. The error message that it should show and redirect to the addProduct page is after the user clicks the submit button for the form. If it redirects to the index form, either success or failure messages will show. If it redirects to the addProduct page - where the form with the submit button is, then neither a success or an error message will show.

Re: Error/Success message not showing on one page in custom module

So I tried something new. If I remove my form from my page, then the Success/Failure messages show up.

But I need my form on my page.

 

Any idea?

Re: Error/Success message not showing on one page in custom module

Ok, I solved it.

I was using

<script type="text/x-magento-init">

for the javascript validation.

I changed it to

<script type="text/javascript">require([
    'jquery',
    'mage/mage'
], function($){

   var dataForm = $('#custom-form');   
dataForm
.mage('validation', {}); }); </script>

 Now it shows all success/failure messages.