I have a page where admin can add a new hospital name to the site, search for the hosiptals and view all the hospitals in a tabular format. This is done by writing custom module and form.

What I now need is to add the value of the newly created hospital to a taxonomy term "hospital". So that I can use this taxonomy term reference in multiple content types.

If admin adds hospital-1 and hospital-2 to the site using custom form, on form submission these should automatically get added to the taxonomy term.

2 Answers 2


To add taxonomy term in form submission, get all inputted term values and those to Vocabulary you need.

use Drupal\taxonomy\Entity\Term;
$categories_vocabulary = 'EXAMPLE'; // Vocabulary machine name
$categories = ['test 1', 'test 2', 'test 3', 'test 4']; // List of test terms
foreach ($categories as $category) {
  $term = Term::create(array(
    'parent' => array(),
    'name' => $category,
    'vid' => $categories_vocabulary,

Inside the form submit handler I do the following operations. First I fetch the vocabulary. Then I search for the new hospital name in that vocabulary. If that name doesn't exists I will save the new term.

$vocabulary = taxonomy_vocabulary_machine_name_load('hospital_names');

$existing_term = taxonomy_get_term_by_name($hospital_name, $vocabulary);

if (empty($existing_term)) { $term1 = (object) array( 'name' => $hospital_name, 'vid' => $vocab->vid, ); taxonomy_term_save($term1); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.