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 DrupaltaxonomyEntityTerm; use DrupalCoreFormFormStateInterface; 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>'); // REPLACE THE NEXT LINE WITH CODE TO SET THE CURRENT TOPIC $form['field_topic']['widget']['#options']['_none'] = 'Click & Select the Current Topic'; return $form; } }