2

I created a form via Drupal 8 API, and I am creating a dropdown of a taxonomy terms which has a parent-child hierarchy. But when i select the taxonomy term, it displays term's parent's tid. This is how i try to display the dropdown:

$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
  if($term->depth == 0){
    $term = $term->name;
  }
  elseif ($term->depth == 1) {
    $term = '-'.$term->name;
  }
  elseif ($term->depth == 2){
   $term = '--'.$term->name;
  }
  elseif ($term->depth == 3){
    $term = '---'.$term->name;
  }
  elseif ($term->depth == 4){
    $term = '----'.$term->name;
  }
  $option[] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

I have been trying to get the term's tid not the parent's tid, can anyone point out what am doing wrong? Note:I am not super experienced with drupal 8

  • You drop replace if/elseif with str_repeat('-', $term->depth) . $term->name. I'd also recommend passing TRUE to that method to load it as entities and then use ->id() and ->label(). – Berdir Mar 2 '17 at 19:21
1

For the further references: I changed my code to this:

$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
$key = $term->id;

if($term->depth == 0){
  $term = $term->name;
}
elseif ($term->depth == 1) {
  $term = '-'.$term->name;
}
elseif ($term->depth == 2){
 $term = '--'.$term->name;
}
elseif ($term->depth == 3){
  $term = '---'.$term->name;
}
elseif ($term->depth == 4){
  $term = '----'.$term->name;
}
 $option[$key] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

Sorry if I wasted your time.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.