Magento: Hiding Payment Methods Based on Shipping Method in OnePage Checkout
In Magento’s OnePage Checkout process, controlling which payment methods are available based on selected shipping options can be quite complex. You’re not alone if you’ve struggled with this. Let’s dive into a detailed solution for hiding the ‘Cash On Delivery’ method when either Flat Rate or Free Shipping is chosen.
Understanding the Magento Event System
The key to achieving your goal lies in observing and manipulating events within Magento’s observer pattern. Specifically, we’ll be working with the payment_method_is_active event fired during checkout.
Configuring Your Observer
First, ensure that your module configuration file (config.xml) is correctly set up:
<frontend>
<events>
<payment_method_is_active>
<observers>
<Kol_PaymentToggle_payment_method_is_active>
<type>singleton</type>
<class>Kol_PaymentToggle_Model_Observer</class>
<method>paymentMethodIsActive</method>
</Kol_PaymentToggle_payment_method_is_active>
</observers>
</payment_method_is_active>
</events>
</frontend>
Here, we’ve mapped the payment_method_is_active event to our observer class Kol_PaymentToggle_Model_Observer.
Implementing the Observer Logic
Now, let’s implement the logic in your observer class:
class Kol_PaymentToggle_Model_Observer
{
public function paymentMethodIsActive(Varien_Event_Observer $observer)
{
$quote = $observer->getEvent()->getQuote();
$shippingMethod = $quote->getShippingAddress()->getShippingMethod();
if (in_array($shippingMethod, ['flatrate_flatrate', 'free'])) {
$method = $observer->getEvent()->getMethodInstance();
if ($method->getCode() == 'cashondelivery') {
$result = $observer->getEvent()->getResult();
$result->isAvailable = false;
}
}
}
}
A few key points here:
- We retrieve the shipping method from the quote object.
- Use
in_arrayto check if the selected shipping method is either ‘flatrate_flatrate’ (Flat Rate) or ‘free’. - If it is, we get the payment method instance and check its code against ‘cashondelivery’.
- If a match is found, we set
$result->isAvailabletofalse, effectively hiding the Cash On Delivery option.
Shipping Method Code Names
Ensure you’re using the correct shipping method codes. In your case:
- Flat Rate:
flatrate_flatrate - Free Shipping:
free
These are Magento’s internal code names for those methods.
Conclusion
With this observer setup and logic, you should now see the Cash On Delivery payment option being automatically hidden whenever a customer selects either the Flat Rate or Free Shipping method during checkout. This keeps your checkout process clean and prevents users from choosing an invalid combination of shipping and payment methods.
Remember to always test these changes thoroughly in a development environment before deploying to production. Happy coding!
For more advanced Magento customizations, consider exploring our professional services at Laravel Company.