Faloude Faloude - 4 months ago 32
PHP Question

SilverStripe $summary_field interupts label translation

I'm using

public function fieldLabels()
in my DataObject to translate all field labels (as well as the labels for
$summary_fields
). This works fine for all fields, except one that has a value returned from a function (rather than value extracted from database).

Summary Fields

static $summary_fields = array(
'Label' => 'Label',
'Type' => 'Type',
'getRequiredLabel' => 'Required'
);


FieldLabels

public function fieldLabels($includerelations = true) {
$labels = parent::fieldLabels(true);

$labels['Label'] = _t('UserForm.Label', 'Label');
$labels['Type'] = _t('UserForm.Type', 'Type');
$labels['Required'] = _t('UserForm.Required', 'Required');

return $labels;
}


All fields are neatly translated through
fieldLabels()
except for Required because this has a custom value from a function rather than from data. Changing getRequiredLabel to Required fixes this.

Any way I can keep the value getRequiredLabel for the record fields and have the translated label in the top column?

enter image description here

Answer

Set $summary_fields getRequiredLabel variable to RequiredLabel and use $field_labels to set the field labels.

private static $summary_fields = array(
    'Label',
    'Type',
    'RequiredLabel'
);

private static $field_labels = array(
    'RequiredLabel' => 'Required'
);

Then in fieldLabels the RequiredLabel column should be accessed with $labels['RequiredLabel'].

public function fieldLabels($includerelations = true) {
    $labels = parent::fieldLabels(true);

    $labels['Label'] = _t('UserForm.Label', 'Label');
    $labels['Type'] = _t('UserForm.Type', 'Type');
    $labels['RequiredLabel'] = _t('UserForm.Required', 'Required');

    return $labels;
}

You could also use the Boolean modifier Nice here to achieve the same effect.

private static $summary_fields = array(
    'Label',
    'Type',
    'Required.Nice'
);

private static $field_labels = array(
    'Required.Nice' => 'Required'
);

public function fieldLabels($includerelations = true) {
    $labels = parent::fieldLabels(true);

    $labels['Label'] = _t('UserForm.Label', 'Label');
    $labels['Type'] = _t('UserForm.Type', 'Type');
    $labels['Required.Nice'] = _t('UserForm.Required', 'Required');

    return $labels;
}