View source
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
class FractionDecimalFormatter extends FractionFormatterBase {
public static function defaultSettings() {
return [
'precision' => 0,
'auto_precision' => TRUE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['precision'] = [
'#type' => 'number',
'#title' => $this
->t('Decimal precision'),
'#description' => $this
->t('Specify the number of digits after the decimal place to display. When "Auto precision" is enabled, this value essentially becomes a minimum fallback precision.'),
'#default_value' => $this
->getSetting('precision'),
'#required' => TRUE,
'#weight' => 0,
];
$elements['auto_precision'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Auto precision'),
'#description' => $this
->t('Automatically determine the maximum precision if the fraction has a base-10 denominator. For example, 1/100 would have a precision of 2, 1/1000 would have a precision of 3, etc.'),
'#default_value' => $this
->getSetting('auto_precision'),
'#weight' => 1,
];
return $elements;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
$precision = $this
->getSetting('precision');
$auto_precision = !empty($this
->getSetting('auto_precision')) ? 'On' : 'Off';
$summary[] = $this
->t('Precision: @precision, Auto-precision: @auto_precision', [
'@precision' => $precision,
'@auto_precision' => $auto_precision,
]);
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$precision = $this
->getSetting('precision');
$auto_precision = !empty($this
->getSetting('auto_precision')) ? TRUE : FALSE;
foreach ($items as $delta => $item) {
$fraction = $item->fraction;
$output = $fraction
->toDecimal($precision, $auto_precision);
$elements[$delta] = [
'#markup' => $this
->viewOutput($item, $output),
];
}
return $elements;
}
}