0

Website on Drupal 8. I have a form for editing the user (on url: user/{user}/edit), I added two checkboxes there, the first checkbox is the driver role, and the second checkbox role is the passenger (for example).

I want that when the user selects for example, the first checkbox, and clicked save. His profile should be updated, and the selected earlier role should be added. And the role of the second is to retire (if it was).

I thought that we can do it, if you assign submit handler role assignment based on a selected checkbox.

but I do not know how to write the code correctly

enter image description here

Jerzy Stuhr
  • 63
  • 2
  • 7

1 Answers1

1

Don't clearly understand what you want but you can do anything in

hook_form_alter()

here is code

/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id){
    case 'user_profile_form':
      $form['#submit'][] = 'user_update_func';

    break;
  }
}

/**
 * submit callback fuction.
 */
function user_update_func($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $currentUser = \Drupal::currentUser();
  $currentUser->addRole('new_selected_role');
  $currentUser->removeRole('old_selected_role');
  $currentUser->save();
}

Hope this helps you

THANKS

code.rider
  • 1,891
  • 18
  • 21
  • Yes, I added checkboxes using the hook form alter . But I do not know how to add a role to the user! The role is selected based on the checkbox that the user has selected. – Jerzy Stuhr May 30 '18 at 12:01
  • i update the answer with example of updating user role – code.rider May 30 '18 at 12:27