1

In a Craft field layout, you can override the label for a field just for that layout/tab. However, when displaying a list of fields on the frontend, I can't find how to get that overridden label, rather than the default for the field.

The code sample below is for a Neo field, but I imagine the same would apply to any field layout. I've tried grabbing the field info from the layout, grabbing the field directly from the fields service, but they both return the original label.

{% set fieldLayoutFields = neoBlock.getFieldLayout().getFields() ??? null %}
{% for fieldLayoutField in fieldLayoutFields %}

    {{ fieldLayoutField.name }}

    {% set field = craft.fields.getFieldById(fieldLayoutField.id) %}

    {{ field.name }}

{% endfor %}

1 Answer 1

2

It's a bit awkward to get overwritten labels, since they're not available in the same place as the regular field names – not even on the same object. The regular name is a property of the field object that extends \craft\base\Field, but the overwritten label is only available on a craft\fieldlayoutelements\CustomField object you can access through the field layout.

Note the difference between those two methods:

{% set fieldLayout = entry.getFieldLayout() %}

{% set customField = fieldLayout.getField('my_custom_field') %}
{% dd customField %}
{# craft\fieldlayoutelements\CustomField #}

{% set field = fieldLayout.getFieldByHandle('my_custom_field') %}
{% dd field %}
{# craft\fields\Categories (or another class extending craft\base\Field) #}

The overwritten label is available through customField.label, the regular label as field.name. If you're not sure if a field has an overwritten label, you can get it like this and fall back to the regular field name:

{% set fieldLayout = entry.getFieldLayout() %}
{% set customField = fieldLayout.getField('my_custom_field') %}
{% set field = fieldLayout.getFieldByHandle('my_custom_field') %}
{% set label = customField.label|default(field.name) %}

If there is a simpler method to access the label with a graceful fallback to the field name, I'd be happy to hear it as well!

1
  • 1
    Thanks so much for the quick response, it worked perfectly!
    – James
    Nov 5, 2021 at 14:13

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.