Skip to main content

Magento: Disable shipping method for PO Box address


UPS will not ship to PO Box addresses. So, we need to disable the UPS if the customer address has PO Box. USPS has to be shown, as it ships to PO Box addresses. So, here is a code on how to disable the shipping method for PO Box address.

Create a new custom module.
First we need to override the class Mage_Usa_Model_Shipping_Carrier_Ups. Add the below code to the new class to dispatch a custom event. This event can be thrown from any carrier class. So, we can re-use it if to disable any other shipping method.


public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request) {

    Mage::dispatchEvent('carrier_process_additional_validation', array('request' => $request, 'carrier' => $this));
    if ($this->getCarrierNotAvailable() === true) {
        return false;
    }

    return parent::proccessAdditionalValidation($request);
}

Add the below code to etc/system.xml file.


<config>
    <sections>
        <carriers>
            <groups>
                <ups>
                    <fields>
                        <po_box_disable translate="label">
                            <label>Disable if PO Box in the address</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>5000</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </po_box_disable>
                    </fields>
                </ups>
            </groups>
        </carriers>
    </sections>
</config>

Catch the event "carrier_process_additional_validation" in the observer.


public function proccessAdditionalValidation($observer) {
    $request = $observer->getEvent()->getRequest();
    $carrier = $observer->getEvent()->getCarrier();

    if ($carrier->getConfigData('po_box_disable')) {
        $street = $request->getData('dest_street');
        if (preg_match("/p(ost)?\.?\s*o(ffice)?\.?\s*(b(ox)?)?\.?\s*\d+/i", $street)) {
            $carrier->setCarrierNotAvailable(true);
        }
    }

    return $this;
}


Comments

Popular posts from this blog

Magento 2 - Create Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .