3

I created my custom controller that perform a post action, when there are some errors I need to send a param with a message to the view, but I can't use the messageManager class, because I need to put these error on a specific place.

I tried to add the error messages using \Magento\Framework\Registry on my Controller, then using my Block I get the registry and I tried to get the param on my .phtml but the variable is always null.

Here my controller: <vendor>\<module>\Controller\Account\LoginPost.php

<?php namespace <vendor>\<module>\Controller\Account; use Magento\Customer\Model\Account\Redirect as AccountRedirect; use Magento\Framework\App\Action\Context; use Magento\Customer\Model\Session; use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Model\Url as CustomerUrl; use Magento\Framework\Exception\EmailNotConfirmedException; use Magento\Framework\Exception\AuthenticationException; use Magento\Framework\Data\Form\FormKey\Validator; class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
/**
 * @var \Magento\Framework\Registry
 */
protected $_coreRegistry;

/**
 * LoginPost constructor.
 * @param Context $context
 * @param Session $customerSession
 * @param AccountManagementInterface $customerAccountManagement
 * @param CustomerUrl $customerHelperData
 * @param Validator $formKeyValidator
 * @param AccountRedirect $accountRedirect
 * @param \Magento\Framework\Registry $registry
 */
public function __construct(
    Context $context,
    Session $customerSession,
    AccountManagementInterface $customerAccountManagement,
    CustomerUrl $customerHelperData,
    Validator $formKeyValidator,
    AccountRedirect $accountRedirect,
    \Magento\Framework\Registry $registry
) {
    parent::__construct($context,
        $customerSession,
        $customerAccountManagement,
        $customerHelperData,
        $formKeyValidator,
        $accountRedirect
    );
    $this->_coreRegistry = $registry;
}

/**
 * Login post action
 *
 * @return \Magento\Framework\Controller\Result\Redirect
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
public function execute()
{

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $baseUrl = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl();
    $refererUrl = explode('?', $this->_redirect->getRefererUrl())[0];
    $previusPageNoError = str_replace($baseUrl, '', $refererUrl);
    $previusPage = $previusPageNoError . '?error=1';

    if ($this->getRequest()->isPost()) {
        $login = $this->getRequest()->getPost('login');
        if (!empty($login['username']) && !empty($login['password'])) {
            try {
                 // some code
            } catch (\Exception $e) {
                $message = __('My error message.');
                $this->_coreRegistry->register('message', $message);
                return $this->_redirect($previusPage);
            }
        } else {
            // some code
        }
    }
}}

Here my Block: <vendor>\<module>\Block\Form\Login.php

<?php namespace <vendor>\<module>\Block\Form; class Login extends \Magento\Customer\Block\Form\Login {

/**
 * @var \Magento\Framework\Registry
 */
protected $_coreRegistry;

/**
 * Login constructor.
 * @param \Magento\Framework\View\Element\Template\Context $context
 * @param \Magento\Customer\Model\Session $customerSession
 * @param \Magento\Customer\Model\Url $customerUrl
 * @param array $data
 */
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Customer\Model\Url $customerUrl,
    \Magento\Framework\Registry $registry,
    array $data = []
)
{
    parent::__construct(
        $context,
        $customerSession,
        $customerUrl,
        $data
    );
    $this->_coreRegistry = $registry;
}

/**
 * @return $this
 */
protected function _prepareLayout()
{
    return $this;
}

public function getRegistryMessage()
{
    return $this->_coreRegistry->registry('message');
}}

The return of the last method (getRegistryMessage()) is always null.

1 Answer 1

1

It's a bit late to answer this, but I thought it could help someone else.

I've had the same issue with registry. Digging this out, I found this explanation https://magento.stackexchange.com/a/44306/51230

The registry stores data to memory which is specific to that request (rather than user or anything else), and persists for the duration of that request only. The principle is very simple really, the Mage class is instantiated as a singleton object for every request and the instantiated Mage object remains in memory, and is accessible in all classes (and templates) until the request completes and the response is sent.

As the object is a singleton, whenever you access it you get the same object. All that is happening is that you are storing values to this object, so when one class stores a value, and another accesses it they are both working on the same object and the second class is able to retrieve the value the first class set.

It's Mage 1, but I suppose it makes sense here.

What I needed was to call a controller on a specific JS event, so the workaround is pretty simple, I passed the product id in POST arguments, but if you can't I suppose you're stuck...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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