1

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!

2
$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');
1
  • It works perfectly. Thanks!
    – GJW80
    Oct 22 '20 at 10:02

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.