Score:2

How can I populate radio options on a form with user entities?

cn flag

I have some user entities and I want to make them available as options to choose in a radio button element on a form.

I can populate the options with a username no problem, so visually I can achieve what I want, but I need to be able to get the user entity that was selected in the form submit function, not just the user name.

I've tried loading the entire user entities into the options array but this throws an error.

I need to to do something like below, but instead of 'entity_autocomplete' it needs to be of type 'radio'

$form['user'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#title' => t('Assign or Unassign a user'),
];

When using the above code, the user entity is the value of the form element when submitted, I need to achieve the same thing using radio buttons.

Score:3
de flag

You build an array of options from user entities:

$options = [];
foreach ($users as $user) {
  $options[$user->id()] = $user->getDisplayName();
}

$form['user'] = [
  '#type' => 'radios',
  '#title' => $this->t('User'),
  '#options' => $options,
];

Then in the submit handler you can get the user ID and load the selected user:

$selected_user = \Drupal\user\Entity\User::load($form_state->get('user'));
thiokol avatar
cn flag
Thanks, works great
I sit in a Tesla and translated this thread with Ai:

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.