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
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