3

Let us say you want to collect a bit more information about users during registration. For example, instead of just username and email, I also want place of residenc. How do I collect and store this data per user? At the end of the day I want to end up with place of residence of each user by doing an easy query.

PS: Currently, I have added extra fields to the form user_register_form, but I don't know how to associate this data with my new user because I don't have the new user id.

What is the right approach? Because I think this should be a trivial Drupal exercise, but am sweating :).

I am using Drupal 7.1.

// implements hook_form_alter()
// user-register-form id the id in html but id that works in php is user_register_form
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
      $form['placeofresidence']= array(
        '#title'=>'where do you stay?',
        '#type' => 'textfield',
        '#required' => true,
      );
      $form['#submit'][]='mycustommodule_submit'; //add to callback submit list
      break;
  }
} 

function mycustommodule_submit($form, &$form_state) {
  $stayswhere=$form_state['values']['placeofresidence']; // how do I associate this with new user?
}

2 Answers 2

7

users are a "fieldable entity" in Drupal 7. Just go to "configuration / people / account settings / manage fields" and add your fields. Make sure to check the "Display on user registration form" box.

For the "place of residence" I recommend the addressfield or location modules.

3

Another way to approach this is use the 'data' field of user. According to the documentation here, you could do something like this. Let's say you have added a new form element to the new user registration form and want to save the data in it for something later after they authenticate themselves successfully for the first time.

function custom_module_user_presave(&$edit, $account, $category) {
  //If the account is being created for the first time
  if (empty($account->original->login)) {
    $edit['data']['custom-field'] = $edit['custom-field'];
  }
}

This information will always be returned on a user_load and can be found in the $user->data array. For this example, it would be in $user->data['custom-field'].

1
  • Actually you dont even need to perform a user_load($uid). The data is always available through the global $user; object
    – Mike
    Jul 12, 2012 at 12:46

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.