0
votes

I have the user-signup disabled on my Drupal 7 website. Only the administrator can create accounts.

I want to add custom fields for a user depending on the role the user has been assigned by the administrator.Now I want to add some fields to the registration system that depend to the role that the admin chosen.

eg: If the admin has created a user account with role A and another account with role B. When the users log-in, user A should be asked to enter phone number whereas the second user should be asked to enter home address.

I tried profile2 module but I could not achieve what I wanted.

2
Hi mahdi alikhasi, Please try to write precise questions! Also @TheodorosPloumis's answer solves what you want. Accept his answer as correct as this helps users with similar issue solve things fasterRishi Dua

2 Answers

2
votes

Use the User_Role_Field module that does exactly what you want. If you need better configuration per role access use the Field_Permissions module.

Notice that after user registration the fields are displayed under user profile and not in registration form. Your question is a bit confusing...

0
votes

There's the conditional_fields module, which sounds like it'll get you most of the way there.

Failing that, I'd say your best bet is to use hook_form_alter() in a custom module. Something like:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    // Define the phone field.
    $form['phone'] = array(
      '#type' => 'textfield', 
      '#title' => t('Phone'), 
      '#size' => 30,
      '#maxlength' => 30,
      'settings' => array(
        '#states' => array(
          // Hide this field when role A isn't checked.
          'invisible' => array(
            ':input[role="A"]' => array('checked' => FALSE),
          ),
        ),
      ),
    );
    // Define home address field
    // [copy the snippet above & tweak to suit...]
  }
}

This is unlikely to work out of the box (I've no drupal environment to hand), but with some adaptation it should get you most of the way there.

The "':input[role="A"]' => array('checked' => TRUE)," line will need the most work, i.e. "role" will need to match the name attribute of the "Roles" checkboxes, and the "A" will need to correspond to A's actual value when checked.

If you've no other form_alter usage in your module, you might also consider replacing the function name with "yourmodule_user_register_form_alter".