test

Comments

saurabh.dhariwal’s picture

To show roles in registration form:


function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['roles']['#access'] = TRUE;

}
Abhay Pai’s picture

Yes thats right it worked for me, but my concern is about

  1. I don't want the user to select it from checkbox, reason for it like the user may select administrator role which i don't want to messup my web app
  2. I want to display it in Select List not in radio niether in checkbox field

Is there any alternative way ?

Dev14.addweb’s picture

Use below code to make it work:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // To grant access to all users
  $form['account']['roles']['#access'] = TRUE;
  // Convert checkbox to select list
  $form['account']['roles']['#type'] = 'select';
  // Remove administrator from options
  foreach ($form['account']['roles']['#options'] as $key => $value) {
    if($value == 'administrator') {
      unset($form['account']['roles']['#options'][$key]);
    }
  }
}
Abhay Pai’s picture

Finally below code worked for me...

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_register_form') {
  	$form['account']['roles']['#title'] = t('UserType');
  	$form['account']['roles']['#access'] = TRUE;
    $form['account']['roles']['#required'] = TRUE;
    $form['account']['roles']['#type'] = 'select';
	
  foreach ($form['account']['roles']['#options'] as $key => $value) {
		if($value == 'administrator') {
		  unset($form['account']['roles']['#options'][$key]);
		}
	  }
  }
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id == 'user_profile_form') {
    $form['account']['roles']['#type'] = 'select';
    $form['account']['roles']['#required'] = TRUE;
  }
}

function mymodule_user_presave(&$edit, $account, $category) {
  if (isset($edit['roles'])) {
    is_array($edit['roles']) ? '' : $edit['roles'] = array ( $edit['roles'] => $edit['roles'], 2 => '1' );
    $edit['roles'] = array_filter($edit['roles']);
  }
}