1

I'm building a front-end form, where I'm displaying on front-end my fields following their layout within the CP:

{% set section = craft.app.sections.getSectionByHandle('handle') %}
{% set fieldLayoutId = section.getEntryTypes[0].getFieldLayout().id %}
{% set fieldLayoutTabs = craft.app.fields.getLayoutTabsById(fieldLayoutId) %}

{% for tab in fieldLayoutTabs %}
    {% for field in tab.elements %}
        {% if field is instance of("craft\\fieldlayoutelements\\CustomField") %}
            <pre>
                {{ dump(field) }}
                </pre>
        {% endif %}
    {% endfor %}
{% endfor %}

On the CP, I showing/hiding some fields based on a Lightswitch value, currently thanks to the Reasons plugin, as there're still no native way.

I would like to be able to get at least these rules on front-end, to be able to build a front-end show/hide feature for my form, using the field layout loop.

Is there any way to get the Reasons' fields settings on front-end? Or is there any alternative to achieve this?

1 Answer 1

1

Reasons is not built to be used on the frontend. But, if you really want to you can get all the Reasons raw data (emphasis on raw) in Twig like this:

{% set reasonsData = craft.app.getPlugins().getPlugin('reasons').reasons.getData() %}

The above would return an array containing the actual conditional rules, in addition to arrays of toggle fields and target fields.

You're probably looking at quite a bit of work to duplicate how Reasons uses this data to hide and show fields, though.

Also, as a word of caution; Reasons will never be supported for Craft 4.0, since conditionals are planned for core. I'm hopeful that there'll be a path for migrating Reasons conditionals to the core feature, but if you're going to use Reasons on the front end in any way, that code will definitely need to be refactored for Craft 4.

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.