/**
* Field item of type 'responsive_class'.
*
* @FieldType(
* id = "responsive_class",
* label = @Translation("Responsive class"),
* module = "responsive_class_field",
* default_widget = "responsive_class_widget",
* default_formatter = "responsive_class_formatter",
* cardinality = 1,
* translatable = FALSE,
* )
*/
class ResponsiveClassItem extends FieldItemBase implements FieldItemInterface {
[...]
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'description' => 'The selected responsive styles.',
'type' => 'blob',
'not null' => TRUE,
'serialize' => TRUE,
],
],
];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = [];
$properties['value'] = DataDefinition::create('responsive_class')
->setLabel(new TranslatableMarkup('Responsive class settings'))
->setRequired(FALSE);;
$properties['classes'] = DataDefinition::create('responsive_class_classes')
->setLabel(new TranslatableMarkup('Generated responsive classes'))
->setComputed(TRUE)
->setReadOnly(TRUE);
return $properties;
}
/**
* {@inheritdoc}
*/
public function getValue() {
$values = parent::getValue();
$values['classes'] = $this->getClasses($values['value']);
return $values;
}
/**
* Generate and return responsive classes.
*
* Uses the 'pattern' field storage setting to generate a class for every
* breakpoint and return them as classes array. The pattern may contain
* the placeholders {breakpoint} and {value} that will be replaced by the
* configured breakpoint values.
*
* @param array $breakpoints
* Array of breakpoint values, whereas every breakpoint value is an
* associative array with the following keys:
* - breakpoint_id: ID of the breakpoint in the breakpoints definition.
* - breakpoint: Replacement value for the {breakpoint} token.
* - value: Replacement value for the {value} token.
*
* @return array
* Array of generated classes.
*/
protected function getClasses(array $breakpoints) {
$pattern = $this->getSetting('pattern');
$classes = [];
foreach ($breakpoints as $value) {
$class = str_replace('{breakpoint}', $value['breakpoint'], $pattern);
$class = str_replace('{value}', $value['value'], $class);
$class = Html::getClass($class);
$classes[] = $class;
}
return $classes;
}
}
While the above approach is working, I have the strong feeling that computed properties aren't intended to just being attached in the getValue()
method. So I'm seeking to improve the source code.