View source
<?php
namespace Drupal\fraction\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
class Fraction extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#size' => 10,
'#element_validate' => [
[
$class,
'validateFraction',
],
],
'#process' => [
[
$class,
'processElement',
],
[
$class,
'processAjaxForm',
],
[
$class,
'processGroup',
],
],
'#pre_render' => [
[
$class,
'preRenderGroup',
],
],
'#theme_wrappers' => [
'container',
],
];
}
public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {
$default_value = $element['#default_value'];
if (isset($default_value) && !self::validateDefaultValue($default_value)) {
throw new \InvalidArgumentException('The #default_value for a fraction element must be an array with "numerator" and "denominator" keys.');
}
$element['#tree'] = TRUE;
$element['#attributes']['class'][] = 'form-type-fraction';
$element['numerator'] = [
'#type' => 'number',
'#title' => t('Numerator'),
'#title_display' => $element['#title_display'],
'#default_value' => $default_value ? $default_value['numerator'] : NULL,
'#required' => $element['#required'],
'#size' => $element['#size'],
'#error_no_message' => TRUE,
];
$element['denominator'] = [
'#type' => 'number',
'#title' => t('Denominator'),
'#title_display' => $element['#title_display'],
'#default_value' => $default_value ? $default_value['denominator'] : NULL,
'#description' => !empty($element['#description']) ?? '',
'#required' => $element['#required'],
'#size' => $element['#size'],
'#error_no_message' => TRUE,
];
unset($element['#size']);
unset($element['#description']);
return $element;
}
public static function validateFraction(&$element, FormStateInterface $form_state, &$complete_form) {
$numerator = $element['numerator']['#value'];
$denominator = $element['denominator']['#value'];
if (empty($denominator) && !empty($numerator)) {
$form_state
->setError($element, t('The denominator of a fraction cannot be zero or empty (if a numerator is provided).'));
}
if (!empty($numerator) && ((string) $numerator < '-9223372036854775808' || (string) $numerator > '9223372036854775807')) {
$form_state
->setError($element, t('The numerator of a fraction must be between -9223372036854775808 and 9223372036854775807.'));
}
if (!empty($denominator) && ((string) $denominator <= '0' || (string) $denominator > '2147483647')) {
$form_state
->setError($element, t('The denominator of a fraction must be greater than 0 and less than 2147483647.'));
}
}
public static function validateDefaultValue($default_value) {
if (!is_array($default_value)) {
return FALSE;
}
if (!array_key_exists('numerator', $default_value) || !array_key_exists('denominator', $default_value)) {
return FALSE;
}
return TRUE;
}
}