public function ViewsResultTreeValues::setTreeValues in Views tree 8.2
Sets tree values given a view and result set.
Parameters
\Drupal\views\ViewExecutable $view: The view object.
\Drupal\views\ResultRow[] $result: The result set.
Return value
array The result.
File
- src/
ViewsResultTreeValues.php, line 29
Class
- ViewsResultTreeValues
- Methods to get result tree based on views results.
Namespace
Drupal\views_treeCode
public function setTreeValues(ViewExecutable $view, array $result) {
$fields = $view->field;
$options = $view
->getStyle()->options;
$parents = [];
if (!$fields[$options['main_field']] instanceof FieldPluginBase) {
$this
->messenger()
->addError($this
->t('Main field is invalid: %field', [
'%field' => $options['main_field'],
]), 'error');
return [];
}
if (!$fields[$options['parent_field']] instanceof FieldPluginBase) {
$this
->messenger()
->addError($this
->t('Parent field is invalid: %field', [
'%field' => $options['parent_field'],
]), 'error');
return [];
}
// The field structure of Field API fields in a views result object is...
// ridiculous. To avoid having to deal with it, we'll first iterate over all
// records and normalize out the main and parent IDs to new properties. That
// vastly simplifies the code that follows. This particular magic
// incantation extracts the value from each record for the appropriate field
// specified by the user. It then normalizes that value down to just an int,
// even though in some cases it is an array. See views_tree_normalize_key().
// Finally, we build up a list of all main keys in the result set so that we
// can normalize top-level records below.
foreach ($result as $i => $record) {
$result[$i]->views_tree_main = $this
->normalizeKey($fields[$options['main_field']]
->getValue($record), $fields[$options['main_field']]);
$result[$i]->views_tree_parent = $this
->normalizeKey($fields[$options['parent_field']]
->getValue($record), $fields[$options['parent_field']]);
$parents[] = $record->views_tree_main;
}
// Normalize the top level of records to all point to 0 as their parent
// We only have to do this once, so we do it here in the wrapping function.
foreach ($result as $i => $record) {
if (!in_array($record->views_tree_parent, $parents)) {
$result[$i]->views_tree_parent = 0;
}
}
// Add the depth onto the result.
foreach ($result as $row) {
$current_row = $row;
$depth = 0;
while ($current_row->views_tree_parent != '0') {
$depth++;
if ($parent_row = $this
->findRowByParent($result, $current_row->views_tree_parent)) {
$current_row = $parent_row;
}
else {
break;
}
}
$row->views_tree_depth = $depth;
}
return $result;
}