PhysicalWidgetBase.php in Physical Fields 8
File
src/Plugin/Field/FieldWidget/PhysicalWidgetBase.php
View source
<?php
namespace Drupal\physical\Plugin\Field\FieldWidget;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
abstract class PhysicalWidgetBase extends WidgetBase {
public static function defaultSettings() {
return [
'default_unit' => '',
'allow_unit_change' => TRUE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['default_unit'] = [
'#type' => 'select',
'#title' => $this
->t('Default unit'),
'#options' => $this
->getUnits(),
'#default_value' => $this
->getSetting('default_unit') ?: $this
->getDefaultUnit(),
];
$element['allow_unit_change'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Allow the user to select a different unit of measurement on forms.'),
'#default_value' => $this
->getSetting('allow_unit_change'),
];
return $element;
}
public function settingsSummary() {
$summary = [];
$summary[] = $this
->t('Default unit: @unit', [
'@unit' => $this
->getDefaultUnit(),
]);
if (!$this
->getSetting('allow_unit_change')) {
$summary[] = $this
->t('User cannot modify the unit of measurement.');
}
else {
$summary[] = $this
->t('User can modify the unit of measurement.');
}
return $summary;
}
protected function getUnits() {
$unit_class = $this
->getUnitClass();
return $unit_class::getLabels();
}
protected function getDefaultUnit() {
$default_unit = $this
->getSetting('default_unit');
if (!$default_unit) {
$unit_class = $this
->getUnitClass();
$default_unit = $unit_class::getBaseUnit();
}
return $default_unit;
}
protected abstract function getUnitClass();
}