1

I have multiple custom shipping methods, each with rules which determine whether or not they will be available to the user. Basic things like minimum order cost and their address which would determine if a certain shipping method is available.

There are some scenarios where a shipping method wont be available and the reason could depend. I need to be able to tell the user what exactly caused it to be unavailable.

So for example:

public function matchOrder(\Craft\Commerce_OrderModel $order){

    // If this is true, do not enable shipping method.
    if($scenario_1) { return false; }

    // If this is true, do not enable shipping method.
    if($scenario_2) { return false; }

    return true;

}

In the event that one of those is true, the shipping method is not available to the user. On the shipping page, I can check if it is enabled or not like this:

{% if 'myShippingMethod' not in craft.commerce.availableShippingMethods|keys %}{% endif %}

But that only does me good in simply whether or not it's available - not for knowing why it isn't available. Is there a way I could somehow 'pass' information to the templates for the shipping methods that didn't return true? That way I could tell user "This shipping method isn't available because of $scenario_1" or "This shipping method isn't available due to $scenario_2."

Does this make sense? Trying to think of a good way to go about this. Any thoughts about how I should go about this would be super appreciated.

1

100% untested, but I think one way to go would be to use addError on one of the Commerce_OrderModel's attributes (in the defineAttributes method).

Then your template could do something like:

{% if 'myShippingMethod' not in craft.commerce.availableShippingMethods|keys %}
    {% for error in order.getErrors('theAttribute') %}
        {{ error }}<br />
    {% endfor %}
{% endif %}
  • Huh, that's a pretty clever idea. I'll run with it and see what I can do! – taylor Oct 11 '16 at 22:23
  • Just tried it - worked perfectly. I love when a solution for something ends up being knowledge that'll help in many other areas down the road. Thanks Brad! – taylor Oct 11 '16 at 22:29
  • Glad to help, @taylor! – Brad Bell Oct 11 '16 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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