I am trying to get the required attribute of a field in a frontend form. I know this attribute only makes sense in the context of an entry type. Doing this


returns a FieldModel object which has no context to any entry type. This way I can get the field name and the instructions for example. In Craft we set the required attribute in the entry type editor. So my question is:

How can I get a field's required attribute in the context of a specific entry type?

Edit: My goal is to create a frontend form of an entry type and have every change to the field's required flags in the backend automatically reflected in the frontend form: <input required ...>.


I could not find a way to get a specific field for a model but you can get all and loop through them

<!-- fetch all fields for your entryType -->
{% for field in craft.entries.section('yourSection').type('yourEntryType').first.getFieldLayout().getFields() %}
    <!-- loop them and check the handle if it is your field -->
    {% if field.getField().handle == "yourFieldHandle" %}
        <!-- the required attribute -->
        {% set required = field.required %}
        {{ field.getField().name }}
        {{ field.getField().instructions }}
    {% endif %}
{% endfor %}

Edit: if you really want to have only one field instead of the array I could create php code for you but since many people refuse to use php in craft I presented the "slower" twig method

Edit: There is a required property in both the FieldLayoutFieldModel (stored above in field) and in the FieldModel (field.getField() above). What we want as the required flag of the entry type is the first: field.required. This is what appears to be the little red asterisk in Craft's backend.

  • Wow, thanks for the fast reply. No I want all fields - was just written generally. What I noticed: Calling getFields() on a FieldLayout returns an array of FieldLayoutFieldModels with the desired property required for this entry type but without properties like name or instructions. These two can only(?) be found in the appropriate FieldModel which I can get with ...getFieldLayout().getFields()[0].field. Wow this gets almost too clunky for a Twig template.
    – Johannes
    Nov 11 '17 at 11:08
  • I updated my answer in order to display the name and the instructions. You just have to use the getField() function Nov 11 '17 at 11:13
  • I updated your answer as there are multiple required properties where field.required is the right one in the example.
    – Johannes
    Nov 11 '17 at 17:33

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.