diff --git a/src/PreloadBuildTrait.php b/src/PreloadBuildTrait.php index b700b25..532c917 100644 --- a/src/PreloadBuildTrait.php +++ b/src/PreloadBuildTrait.php @@ -3,6 +3,7 @@ namespace Drupal\select2boxes; use Drupal\Core\Field\FieldDefinitionInterface; +use Drupal\taxonomy\Plugin\views\wizard\TaxonomyTerm; /** * Trait PreloadBuildTrait. @@ -25,6 +26,16 @@ trait PreloadBuildTrait { * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException */ protected function buildPreLoaded($count, FieldDefinitionInterface $fieldDefinition) { + // Get settings info. + $settings = $fieldDefinition->getSettings(); + $target_type = $settings['target_type']; + + // If target entity type is taxonomy_term. + if ($target_type === 'taxonomy_term') { + $entities = $this->handleTaxonomyTerms($settings); + return !empty($entities) ? $entities : []; + } + $entities = []; // Return empty array if the count is less than 1. if ($count <= 0 && $count != '') { @@ -49,4 +60,73 @@ trait PreloadBuildTrait { return $entities; } + /** + * Build preloaded entries for taxonomy terms. + * + * @param array $settings + * Field settings to take into account + * + * @return array + * Preloaded entries list array. + */ + private function handleTaxonomyTerms($settings) { + $vocabs = $settings['handler_settings']['target_bundles']; + + // Prepare parent and child arrays as needed for later computation. + /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */ + $term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); + foreach ($vocabs as $key => $value) { + $data = $term_storage->loadTree($key); + foreach ($data as $item) { + if ($item->depth == 0) { + $root_terms[$item->name] = ['id' => $item->tid, 'text' => $item->name]; + } + else { + $parent_term = $term_storage->load($item->parents[0]); + $children[$item->name] = [ + 'id' => $item->tid, + 'text' => $item->name, + 'depth' => $item->depth, + 'parent' => $item->parents[0], + ]; + // Terms which are both parents to some and child to other terms. + if ($parent_term) { + $parents[] = $parent_term->id(); + $root_terms[$parent_term->label()] = [ + 'id' => $parent_term->id(), + 'text' => $parent_term->label(), + ]; + } + } + } + } + + // Sort both parent and child terms alphabetically. + ksort($root_terms); + ksort($children); + + // Manage parent child placement to maintain proper parent-child placement. + // Keep track of terms covered to avoid duplicates. + $done = []; + $result = []; + foreach($root_terms as $root_term) { + if (!in_array($root_term['id'], $done)) { + $result[] = $root_term; + $done[] = $root_term['id']; + } + if (in_array($root_term['id'], $parents)) { + foreach ($children as $child) { + if ($child['parent'] === $root_term['id'] && !in_array($child['id'], $done)) { + $result[] = [ + 'id' => $child['id'], + 'text' => str_repeat('-', $child['depth']) . $child['text'], + ]; + $done[] = $child['id']; + } + } + } + } + return array_values($result); + } + }