public static function TermReferenceTree::validateTermReferenceTreeElement in Taxonomy Term Reference Tree Widget 8
Form element validation handler for term reference form widget.
File
- src/
Plugin/ Field/ FieldWidget/ TermReferenceTree.php, line 174
Class
- TermReferenceTree
- Plugin implementation of the 'term_reference_tree' widget.
Namespace
Drupal\term_reference_tree\Plugin\Field\FieldWidgetCode
public static function validateTermReferenceTreeElement(&$element, FormStateInterface $form_state) {
$items = _term_reference_tree_flatten($element, $form_state);
$value = [];
if ($element['#max_choices'] != 1) {
foreach ($items as $child) {
if (!empty($child['#value'])) {
// If the element is leaves only and select parents is on,
// then automatically add all the parents of each selected value.
if (!empty($element['#select_parents']) && !empty($element['#leaves_only'])) {
foreach ($child['#parent_values'] as $parent_tid) {
if (!in_array([
$element['#value_key'] => $parent_tid,
], $value)) {
array_push($value, [
$element['#value_key'] => $parent_tid,
]);
}
}
}
array_push($value, [
$element['#value_key'] => $child['#value'],
]);
}
}
}
else {
// If it's a tree of radio buttons, they all have the same value,
// so we can just grab the value of the first one.
if (count($items) > 0) {
$child = reset($items);
if (!empty($child['#value'])) {
array_push($value, [
$element['#value_key'] => $child['#value'],
]);
}
}
}
if ($element['#required'] && empty($value)) {
$form_state
->setError($element, t('%name field is required.', [
'%name' => $element['#title'],
]));
}
$form_state
->setValueForElement($element, $value);
}