Drupal - How can add a textfield to user/register page form in drupal 7?

Drupal 7 provides the ability to add custom fields to the User through admin/config/people/accounts/fields. This functionality should already be in core.


I would rather implement hook_form_FORM_ID_alter() to add the form field.

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['address'] = array('#type' => 'textfield',
    '#title' => t('Your address'),
    '#size' => 60,
    '#maxlength' => 125,
    '#required' => TRUE,
  );
}

In this way, the form field will be added to the registration form.


Example on how to programatically add fields to the user profile and how to avail them, or not, into the User Registration form.

function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {
    $field = array(
      'field_name' => 'field_myField', 
      'type' => 'text', 
    );

    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField', 
      'entity_type' => 'user', 
      'label' => 'My Field Name', 
      'bundle' => 'user', 
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ), 
    );

    field_create_instance($instance);
  }
}

Tags:

Forms