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?