Get the form to add a term to a vocabulary programmatically
-
28-02-2021 - |
문제
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!
해결책
$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');
제휴하지 않습니다 drupal.stackexchange