1

How do I access a subscription plan's planData? Maybe as an object? I'm using Commerce 2 with the Stripe gateway.

For example:

{% set plans = craft.commerce.getPlans().getAllPlans() %}
{% for plan in plans %}
    {{ dump(plan.planData) }}
{% endfor %}

planData looks like JSON stored as a string. How do I access its data (amount, trial_period_days etc.) on the front end?

Does this need to be handled by a custom plugin? Seems like something that should be available out of the box. Hopefully I just over looked it.

1 Answer 1

3

A subscription's planData is currently only stored as JSON. You can use that JSON in your template but you'll need to decode it first. Marion Newlevant’s Twig Perversion plugin adds a json_decode filter among other helpful capabilities to Twig.

With that plugin installed, set planData to a variable with the json_decode filter applied to it then you can access attributes of planData as you normally would in Twig.

{% set plans = craft.commerce.getPlans().getAllPlans() %}
{% for plan in plans %}
    {% set planData = plan.planData|json_decode %}
    {{ planData.plan.amount }}
    {# Stripe stores the amount as cents, so formatting for dollars or euros might look like this #}
    {{ (planData.plan.amount / 100)|currency }}
    {# Trial period  #}
    {{ planData.plan.trial_period_days }}
{% endfor %}
3
  • Doesn't look like |json_decode is a native Twig filter. Looks like this plugin adds it though (not sure if it supports Craft 3). github.com/diit/Json-Decode-Twig I was hoping there was native support. Commented Oct 27, 2018 at 19:27
  • 1
    @SimonKuran — You are correct. I thought it was native in Craft 3, but I have Marion Newlevant’s Twig Perversion plugin installed which adds a json_decode filter and other helpful capabilities to Twig. Updated my answer with this info. Commented Oct 27, 2018 at 22:33
  • 1
    I believe that json_decode filter is now native (at least as of Craft 3.1.30)
    – SoHo
    Commented Jun 17, 2019 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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