I wrote module with hook_form_alter to modify node_forum_form, i.e., node/add/forum form. One forum field is a taxonomy entity reference, field_topic. I want to set the field_topic selection based on the value from a specific node (NID=77) of type current_topic, which also has field_topic as an entity ref.

field_topic is ref to Topic taxonomy.

After loading node 77, I got the TID of the current_topic field_topic, loaded the term, and then got the term name. Name is displayed on the form above the title using $form['title']['#markup'].

Problem: Before returning the form, how can I set the form default selection to be that same field_topic value?

use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id != 'node_forum_form') {
    return FALSE;
  else {
    $nid = 77;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); //get the TID
    $term = Term::load($current_topic_id);
    $the_topic = $term->getName();

    $form['title']['#markup'] = t('<h3>The Current Topic is:  <i>' . $the_topic . '</i></h3>');

    $form['field_topic']['widget']['#options']['_none'] = 'Click & Select the Current Topic';

    return $form;

2 Answers 2


I suppose with

set the form selection

you mean the default value of the taxonomy term reference field?

If yes, in the code above try this:

$form['field_topic']['widget']['#default_value'] = $term->tid();

Btw. you also want to change your implementation from MYMODULE_form_alter to MYMODULE_form_node_forum_form_alter, because the former hook will be called for all forms, whereas the latter is just called when the forum node form renders.

  • Thanks for your suggestion. With a small change it worked perfectly! $form['field_topic']['widget']['#default_value'] = $current_topic_id; Oct 8, 2018 at 18:22

The $term->tid() was calculated earlier in the code. That was the solution.

  • While this all works perfectly for admin users, authenticated users see only '- Select a value -' as the default value. I verified with set_message that the code knows the correct default value of the taxonomy term. What could be causing this? Nov 8, 2018 at 1:36
  • Note in case of authenticated user, <option value="_none"> is the only item in the select list. For admin user, the select list contains all of the taxonomy items with the correct option value set to selected="selected". Nov 8, 2018 at 1:54

Your Answer

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

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