unclecheese / silverstripe-display-logic

The Display Logic module allows you to add conditions for displaying or hiding certain form fields based on client-side behavior.
BSD 3-Clause "New" or "Revised" License
74 stars 71 forks source link

feat(setMaster): Add 'setMaster' function so that referenced field names can be rewritten. #73

Closed silbinarywolf closed 7 years ago

silbinarywolf commented 7 years ago

feat(setMaster): Add 'setMaster' function so that referenced field names can be rewritten. (ie. I might rewrite a group of fields to have an alternate name with setName() and I want the display logic referenced names to also match the change)

Below is how I'll use this PR in my own MultiRecordField module.

/**
 * Re-write field names to be unique
 * ie. 'Title' to be 'ElementArea__MultiRecordField__ElementGallery__Title'
 *
 * @return \MultiRecordField
 */
public function applyUniqueFieldNames($fields, $record)
{
    $hasDisplayLogic = $this->hasMethod('getDisplayLogicCriteria');
    $isReadonly = $this->isReadonly();
    foreach ($fields->dataFields() as $field)
    {
        // Get all fields underneath/nested in MultiRecordSubRecordField
        $name = $this->getUniqueFieldName($field, $record);
        $field->setName($name);

        // Support Display Logic module by Unclecheese
        if ($hasDisplayLogic) {
            $displayLogicCriteria = $field->getDisplayLogicCriteria();
            if ($displayLogicCriteria !== null) {
                $displayLogicFieldName = $displayLogicCriteria->getMaster();
                $displayLogicFieldName = $this->getUniqueFieldName($displayLogicFieldName, $record);
                $displayLogicCriteria->setMaster($displayLogicFieldName);
            }
        }
    }
    foreach ($fields as $field)
    {
        // This loop is at a top level, so it should all technically just be
        // MultiRecordSubRecordField's only.
        if ($field instanceof MultiRecordSubRecordField) {
            $name = $this->getUniqueFieldName($field, $record);
            $field->setName($name);
        }
        if ($isReadonly) {
            $fields->replaceField($field->getName(), $field = $field->performReadonlyTransformation());
        }
    }
    return $this;
}