Question

I am working on Drupal 8.9.6.

I am trying to retrieve the form to add a term to a vocabulary programmatically. I know how to do it for a content type:

    $values = array('type' => $content_type);

    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create($values);

    $form = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity($node);
    $modal_form =  \Drupal::formBuilder()->getForm($form);

Nevertheless, I am not able to do the same for the form of adding a term to a vocabulary. Any hint would be more than welcome.

Thanks!

Was it helpful?

Solution

$vocab_machine_name = 'tags';
$values = array('vid' => $vocab_machine_name);

$term = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('taxonomy_term', 'default')
  ->setEntity($term);

$term_form =  \Drupal::formBuilder()->getForm($form);

Shorter way

$vocab_machine_name = 'tags';

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => $vocab_machine_name,
]);

$term_form = \Drupal::service('entity.form_builder')->getForm($term, 'default');
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top