2

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.

1 Answer 1

3

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'));
1

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.