Magento – Show error message on shipping method if not applicable in Magento 2

magento2magento2.2shipping-methods

I have developed custom shipping module. Now I want to show error message on shipping module if anything wrong like city, state, phone number etc.

I follow this link to create shipping method: https://www.mageplaza.com/magento-2-create-shipping-method/

How do I achieve this?

Best Answer

Override checkAvailableShipCountries() at

app/code/Vendor/Module/Model/Carrier/Myshipping.php

Here you can get city, state, country etc from \Magento\Framework\DataObject $request

Use $this->_rateErrorFactory for display error

Final Code:

public function checkAvailableShipCountries(\Magento\Framework\DataObject $request)
{
    $allowedCity = "ahmedabad,surat,morbi";
    $allowedCity = explode(',', $allowedCity);

    if(in_array($request->getDestCity(), $allowedCity)) {
        return $this;
    } else {
        $error = $this->_rateErrorFactory->create();
        $error->setCarrier($this->_code);
        $error->setCarrierTitle($this->getConfigData('title'));
        $errorMsg = $this->getConfigData('specificerrmsg');
        $error->setErrorMessage(__(
                'Sorry, but we can\'t deliver to the destination city with this shipping module.'
            )
        );
        return $error;
    }

    return $this;
}
Related Topic