GeofieldElementBase.php in Geofield 8
File
src/Element/GeofieldElementBase.php
View source
<?php
namespace Drupal\geofield\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
abstract class GeofieldElementBase extends FormElement {
public static function getComponents() {
return [];
}
public static function elementProcess(array &$element, FormStateInterface $form_state, array &$complete_form) {
$element['#tree'] = TRUE;
$element['#input'] = TRUE;
foreach (static::getComponents() as $name => $component) {
$element[$name] = [
'#type' => 'textfield',
'#title' => $component['title'],
'#required' => !empty($element['#required']) ? $element['#required'] : FALSE,
'#default_value' => isset($element['#default_value'][$name]) ? $element['#default_value'][$name] : '',
'#attributes' => [
'class' => [
'geofield-' . $name,
],
],
];
}
unset($element['#value']);
$element['#required'] = FALSE;
return $element;
}
public static function elementValidate(array &$element, FormStateInterface $form_state, array &$complete_form) {
$error_label = isset($element['#error_label']) ? $element['#error_label'] : $element['#title'];
foreach (static::getComponents() as $key => $component) {
if (!empty($element[$key]['#value']) && !is_numeric($element[$key]['#value'])) {
$form_state
->setError($element[$key], t('@title: @component_title is not valid.', [
'@title' => $error_label,
'@component_title' => $component['title'],
]));
}
elseif (is_numeric($element[$key]['#value']) && abs($element[$key]['#value']) > $component['range']) {
$form_state
->setError($element[$key], t('@title: @component_title is out of bounds (@bounds).', [
'@title' => $error_label,
'@component_title' => $component['title'],
'@bounds' => '+/- ' . $component['range'],
]));
}
}
}
}