Score:0

Set ['#default_value'] of taxonomy term reference field via hook_form_alter()?

nr flag

Here's a different question with the same taxonomy term reference field I mentioned in my previous question.

Users with Administrator and Coach roles are granted permission to register Student users via a custom "Add student" form mode (user_add_student_form). It would be better for UX if I could set the ['#default_value'] of the select_a_school taxonomy term reference field to the same school that the currently logged in user belongs to.

I'm working with hook_form_alter() in template preprocess because that's how the previous developer set it up:

/**
 * Implements hook_form_alter().
 */
function projectname_form_alter(&$form, &$form_state, $form_id) {
  // Get the current User.
  $current_user_proxy = \Drupal::currentUser();
  $current_user_id = $current_user_proxy->id();
  if (!$current_user_proxy->isAnonymous()) {
    $currentUser = User::load($current_user_id);
    // Get the current User's school.
    $currentSchool = $currentUser->field_select_a_school->getValue();
    // Handle Add Student form.
    if ($form_id == 'user_add_student_form') {
      // This works.
      $form['account']['roles']['#access'] = FALSE;
      $form['account']['roles']['#default_value'] = [
        0 => 'authenticated',
        1 => 'student',
      ];
      // This does not work.
      $form['field_select_a_school']['#default_value'] = $currentSchool;
    }

Setting $form['account']['roles']['#default_value'] works as expected, but the taxonomy term reference field resists all such attempts.

I've tried the following variations:

      $form['field_select_a_school']['#default_value'] = $currentSchool;
      $form['field_select_a_school']['#default_value'][] = $currentSchool;
      $form['field_select_a_school']['widget']['#default_value'] = $currentSchool;
      $form['field_select_a_school']['widget']['#default_value'][] = $currentSchool;
      dump($currentSchool);

The Symfony VarDumper dump() of $currentSchool looks like it contains the correct data structure:

^ array:1 [▼
  0 => array:1 [▼
    "target_id" => "916"
  ]
]

Here, for reference, is the corresponding dump() for the target field in $form:

  "field_select_a_school" => array:8 [▼
    "#type" => "container"
    "#parents" => array:1 [▶]
    "#attributes" => array:1 [▶]
    "widget" => array:22 [▼
      "#title" => "Select A School*"
      "#description" => ""
      "#field_parents" => []
      "#required" => true
      "#delta" => 0
      "#weight" => 0
      "#element_validate" => array:1 [▶]
      "#key_column" => "target_id"
      "#type" => "select"
      "#options" => array:47 [▶]
      "#default_value" => []
      "#multiple" => false
      "#shs" => array:7 [▶]
      "#attributes" => array:1 [▶]
      "#attached" => array:1 [▶]
      "#entity_type" => "user"
      "#bundle" => "user"
      "#after_build" => array:1 [▶]
      "#field_name" => "field_select_a_school"
      "#parents" => array:1 [▶]
      "#tree" => true
      "#form_id" => "user_add_student_form"
    ]
    "#access" => true
    "#weight" => 22
    "#cache" => array:3 [▶]
    "#form_id" => "user_add_student_form"
  ]

No matter what I try, $form['field_select_a_school']['widget']['#default_value'] always ends up containing an empty array. ¯\_(ツ)_/¯

What am I missing here?

cn flag
From your copy/pastes it's `$form['field_select_a_school']['widget']['#default_value'] = $currentSchool[0]['target_id'];` (or `$form['field_select_a_school']['widget']['#default_value'][] = $currentSchool[0]['target_id'];` if a multi-value field)
hotwebmatter avatar
nr flag
Huh, I just assumed I'd need to match the whole data structure rather than just pass the TID. I'll try this, thanks!
hotwebmatter avatar
nr flag
Nice try @Clive but I added `$form['field_select_a_school']['widget']['#default_value'] = $currentSchool[0]['target_id'];` and I'm still getting `"#default_value" => []`.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.