Skip to content

Instantly share code, notes, and snippets.

@smarulanda97vmlyr
Created January 27, 2021 16:29
Show Gist options
  • Save smarulanda97vmlyr/22b1d87266fc1b71428b6b89ee90bece to your computer and use it in GitHub Desktop.
Save smarulanda97vmlyr/22b1d87266fc1b71428b6b89ee90bece to your computer and use it in GitHub Desktop.

Revisions

  1. smarulanda97vmlyr created this gist Jan 27, 2021.
    85 changes: 85 additions & 0 deletions LoadTaxonomyTermsTrait.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    <?php
    /**
    * @file contains \Drupal\africa_tanzania_base\Trait\LoadTermsTrait;
    */
    namespace Drupal\africa_tanzania_base;

    use Drupal\taxonomy\TermInterface;
    use Drupal\Core\TypedData\Exception\MissingDataException;
    use Drupal\Component\Plugin\Exception\PluginNotFoundException;
    use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;

    trait LoadTaxonomyTermsTrait
    {
    /**
    * This method returns an array with all terms of taxonomy, the array contains a basic
    * properties of taxonomy such as name, weight, UUID and an id.
    *
    * @param $vid
    * The vid of the taxonomy
    *
    * @param $fields
    * Optionally you can pass an array with the name of custom fields of taxonomy term and this method
    * returns the value of those fields
    *
    * @param $order
    * By default the array that returns this function is sorted ascending by weight of taxonomy term
    *
    * @return array;
    */
    public function getTaxonomyTerms(string $vid, $fields = [], $order = 'ASC') : array {
    $items = [];

    try {
    $entityStorage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
    $queryResults = $entityStorage->getQuery()
    ->condition('vid', $vid)
    ->sort('weight', $order)
    ->execute();

    foreach ($entityStorage->loadMultiple($queryResults) as $term) {
    /** @var TermInterface $term */
    $tid = $term->id();
    $items[$tid] = $this->getBasicPropertiesOfTerm($term) + $this->getCustomFieldsOfTerm($term, $fields);
    }
    } catch (InvalidPluginDefinitionException | PluginNotFoundException | MissingDataException $e) {
    \Drupal::logger('custom_module')->error($e->getMessage());
    }

    return $items;
    }

    /**
    * @param TermInterface $term
    * Getting the most common properties in a taxonomy term and return as an array
    *
    * @return array
    */
    public function getBasicPropertiesOfTerm(TermInterface $term) : array {
    return [
    'id' => $term->id(),
    'uuid' => $term->uuid(),
    'name' => $term->getName(),
    'weight' => $term->getWeight(),
    ];
    }

    /**
    * @param TermInterface $term
    * @param array $fields
    * An array with the name of fields that would like to extract from taxonomy term
    * The names of the field can't contain the prefix field_
    *
    * @return array
    * @throws MissingDataException
    */
    public function getCustomFieldsOfTerm(TermInterface $term, array $fields) : array {
    foreach ($fields as $field) {
    if (!$term->hasField("field_$field") || $term->get("field_$field")->isEmpty())
    continue;

    $data["field_$field"] = $term->get("field_$field")->first()->getValue()['value'];
    }
    return !isset($data) ? [] : $data;
    }
    }