2

Is it possible, on a model, to get only the fields that were marked as required?

For example I have an entry which has just been saved and I can get it's content like:

$entry->getContent()->getAttributes()

But I need to filter it out by the only the fields that were required, because it already has a section assigned and is saved I thought this might be possible...I tried $entry->getRequiredFields() but that didn't work.

So then I tried these to no avail

$entry->getContent()->getRequiredAttributes()
$entry->getContent()->getRequiredFields()
$entry->getRequiredAttributes()

Is this actually achievable? any help or pointers would be much appreciated! :)

1 Answer 1

3

Your $entry variable – i.e. an instance of EntryModel – has an attribute called fieldLayout, which will return the field layout (FieldLayoutModel) for this entry.

Via the field layout, you can loop over all fields for the entry (each field will be an instance of FieldLayoutFieldModel), checking their required attribute:

// Get all fields for this entry
$fields = $entry->fieldLayout->fields;

// Loop over fields, check required attribute
$requiredFields = array();
foreach ($fields as $fieldModel) {
    if ($fieldModel->required) {
        $requiredFields[] = $fieldModel->field;
    }
}

In the above example, $requiredFields will be an array of required fields, i.e. FieldLayoutFieldModels. If you only need an array of the required attribute names for your entry, you can opt to only store the field handles:

$requiredAttributes = array();
foreach ($fields as $fieldModel) {
    if ($fieldModel->required) {
        $requiredAttributes[] = $fieldModel->field->handle;
    }
}
2

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.