public static function CshsElement::validateElement in Client-side Hierarchical Select 8.2
Same name and namespace in other branches
- 8.3 src/Element/CshsElement.php \Drupal\cshs\Element\CshsElement::validateElement()
- 8 src/Element/CshsElement.php \Drupal\cshs\Element\CshsElement::validateElement()
File
- src/
Element/ CshsElement.php, line 109
Class
- CshsElement
- Defines the CSHS element.
Namespace
Drupal\cshs\ElementCode
public static function validateElement(array &$element, FormStateInterface $form_state) : void {
$term_id = $element['#value'];
if (\is_array($term_id)) {
$term_id = \end($term_id);
}
// The value is not selected.
if (empty($term_id) || $term_id == $element['#none_value']) {
// Element must have its "none" value when nothing selected. This will
// let it function correctly, for instance with views. Otherwise it could
// lead to illegal choice selection error.
/* @link https://www.drupal.org/node/2882790 */
$form_state
->setValueForElement($element, \is_a($form_state
->getFormObject(), ViewsExposedForm::class) ? $element['#none_value'] : NULL);
// Set an error if user doesn't select anything and field is required.
if ($element['#required']) {
$form_state
->setError($element, \t('@label field is required.', [
'@label' => $element['#label'],
]));
}
}
elseif ($element['#force_deepest']) {
$storage = static::getTermStorage();
if (!$storage
->load($term_id)) {
$form_state
->setError($element, \t('Unable to load a term (ID: @id) for the @label field.', [
'@id' => $element['#value'],
'@label' => $element['#label'],
]));
}
elseif (!empty($storage
->loadChildren($term_id))) {
$form_state
->setError($element, \t('You need to select a term from the deepest level in @label field.', [
'@label' => $element['#label'],
]));
}
}
elseif ($element['#required_depth'] > 0) {
$storage = static::getTermStorage();
if (\count($storage
->loadAllParents($term_id)) < $element['#required_depth']) {
$form_state
->setError($element, \t('The field @label requires you to select at least @level levels of hierarchy.', [
'@label' => $element['#label'],
'@level' => $element['#required_depth'],
]));
}
}
}