Hi i have use a plugin feature in my module to check the zipcode is available in the module or not .Which works fine but on validating i have set the error message like
<?php
namespace Company\Mymodule\Plugin\Checkout\Model;
use Magento\Framework\Exception\NoSuchEntityException;
class ShippingInformationManagement
{
protected $_messageManager;
protected $jsonResultFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
$this->_messageManager = $messageManager;
$this->jsonResultFactory = $jsonResultFactory;
}
public function beforeSaveAddressInformation(
\Magento\Checkout\Model\ShippingInformationManagement $subject,
$cartId,
\Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
)
{
$address = $addressInformation->getShippingAddress();
$postcode = $address->getData('postcode');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION');
$result1 = $connection->fetchAll("SELECT shipregioncodes FROM shipregioncodes_shipregioncodes WHERE shipregioncodes=$postcode");
$count = count($result1);
$result = $this->jsonResultFactory->create();
if($count==0){
$this->_messageManager->addError("hiiiiiiii");
throw new NoSuchEntityException(
__('Shipping is not available on provided zipcode %1', $postcode)
);
}
}
}
di.xml code is below
<type name="Magento\Checkout\Model\ShippingInformationManagement">
<plugin name="get_shipping_info" type="Company\Mymodule\Plugin\Checkout\Model\ShippingInformationManagement" sortOrder="1"/>
</type>
it only shows the message in the console not on the site.Please suggest me how can i fix this.
thanks
Best Answer
If it's checkout and it is displayed in console it's possible that is ajax. Maybe try to send back html with text of messages in json an then display it using javascript file responsible for this section of page. Search in core controllers for example of json response cooperating with message manager.
EDIT
Here you have my controller class for custom newsletter ajax module:
}
Key is here:
I get message block and prepare error flag. After that you can see that in case of any exception in
catch
blocks I change value of error flag. In the end I set messages frommessageManager
to my message block and add it to my json response:After that in my javascript, which gets response from controller I inject into DOM block with messages if flag is
true
- in blocksuccess
:Please note that it is done outside of checkout so it can give some directions and advices but you would not be able to adopt it completely. Although it show message manager can be used in ajax calls.