public function WidgetDefaults::getParentDefaults in Simple hierarchical select 2.0.x
Same name and namespace in other branches
- 8 src/WidgetDefaults.php \Drupal\shs\WidgetDefaults::getParentDefaults()
Load parents for default values.
Parameters
array|string $default_values: List of default values of the widget.
string $any_value: The value to assign to "any value".
string $entity_type: The entity type the select is displaying.
int $cardinality: The field's cardinality.
Return value
array List of parents for each default value.
Overrides WidgetDefaultsInterface::getParentDefaults
File
- src/
WidgetDefaults.php, line 75
Class
- WidgetDefaults
- Helper class for setting default values on SHS widgets.
Namespace
Drupal\shsCode
public function getParentDefaults($default_values, $any_value, $entity_type, $cardinality = 1) {
$parents = [];
if (!is_array($default_values)) {
$default_values = [
$default_values,
];
}
foreach ($default_values as $delta => $value) {
if ($any_value === $value) {
$parents[$delta] = [
[
'parent' => 0,
'defaultValue' => $any_value,
],
];
continue;
}
try {
$parent_terms = array_reverse(array_keys(shs_term_load_all_parents($value)));
$keys = array_merge([
0,
], $parent_terms);
$values = array_merge($parent_terms, [
$value,
]);
$parents[$delta] = [];
foreach ($keys as $index => $key) {
$parents[$delta][] = [
'parent' => $key,
'defaultValue' => $values[$index] ?: $any_value,
];
}
} catch (\Exception $ex) {
$parents[$delta] = [
[
'parent' => 0,
'defaultValue' => $any_value,
],
];
}
}
// Populate the parents array so it's equal to the field's cardinality.
if ($cardinality < 0) {
$cardinality = 1;
}
$parents_count = count($parents);
if ($parents_count >= $cardinality) {
return $parents;
}
for ($i = 1; $i <= $cardinality - $parents_count; $i++) {
$parents[] = [
[
'parent' => 0,
'defaultValue' => $any_value,
],
];
}
return $parents;
}