Fraction.php in Fraction 8
File
src/Plugin/views/field/Fraction.php
View source
<?php
namespace Drupal\fraction\Plugin\views\field;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ResultRow;
use Drupal\fraction\Fraction as FractionClass;
class Fraction extends FieldPluginBase {
protected function defineOptions() {
$options = parent::defineOptions();
$options['precision'] = [
'default' => 0,
];
$options['auto_precision'] = [
'default' => TRUE,
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['precision'] = [
'#type' => 'textfield',
'#title' => t('Precision'),
'#description' => t('Specify the number of digits after the decimal place to display when converting the fraction to a decimal. When "Auto precision" is enabled, this value essentially becomes a minimum fallback precision.'),
'#default_value' => $this->options['precision'],
];
$form['auto_precision'] = [
'#type' => 'checkbox',
'#title' => t('Auto precision'),
'#description' => 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->options['auto_precision'],
];
parent::buildOptionsForm($form, $form_state);
unset($form['click_sort_column']);
}
public function clickSort($order) {
$this
->ensureMyTable();
$formula = $this->tableAlias . '.' . $this->definition['additional fields']['numerator'] . ' / ' . $this->tableAlias . '.' . $this->definition['additional fields']['denominator'];
$this->query
->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_decimal');
}
public function getValue(ResultRow $values, $field = NULL) {
$numerator_alias = $this->aliases[$this->definition['additional fields']['numerator']];
$denominator_alias = $this->aliases[$this->definition['additional fields']['denominator']];
if (isset($values->{$numerator_alias}) && isset($values->{$denominator_alias})) {
$numerator = $values->{$numerator_alias};
$denominator = $values->{$denominator_alias};
$precision = $this->options['precision'];
$auto_precision = $this->options['auto_precision'];
$fraction = new FractionClass($numerator, $denominator);
return $fraction
->toDecimal($precision, $auto_precision);
}
}
}
Classes
Name |
Description |
Fraction |
Field handler for Fraction database columns. |