You are here

function NodeTerms::cascadeTerms in Taxonomy Facets 8

1 call to NodeTerms::cascadeTerms()
NodeTerms::findFieldToCascadeTerms in src/NodeTerms.php
Check node fields for Taxo Faceted fields.

File

src/NodeTerms.php, line 76

Class

NodeTerms

Namespace

Drupal\taxonomy_facets

Code

function cascadeTerms($filed_name) {

  // print_r($filed_name);
  $terms = $this->node->{$filed_name}
    ->getValue();
  $parents = [];
  foreach ($terms as $term) {

    // print_r($term);
    $parents = array_merge($parents, $this::getTermParents($term['target_id']));
  }
  $all_parents = array_unique($parents);

  // getTermParents returns a term in question so If more than one, i.e if
  // there are parents than cascade
  if (count($all_parents) >= 2) {

    // Get term out if it was already in the node before editing,
    // we don't want to add it twice.
    $old_terms = [];
    if ($this->old_node) {
      $old_terms = $this->old_node->{$filed_name}
        ->getValue();
    }
    $old_terms_array = [];
    foreach ($old_terms as $old_term) {
      $old_terms_array[] = $old_term['target_id'];
    }
    $all_parents = array_diff($all_parents, $old_terms_array);

    // Convert to associative array.
    // $terms = [];
    foreach ($all_parents as $per) {

      // $terms[] = ['target_id' => $per];
      $this->node->{$filed_name}[] = [
        'target_id' => $per,
      ];
    }
  }
}