Set default value to an input field drupal 7

1.5k Views Asked by At

I began a project which uses Entity Registration. An authenticated user can register for him and some else for an event. I set some extra fields in the account creation (name and surname).

I also set name and surname for registering to an event. I'd like to avoid an authentificated user to fill twice a form with same information.

For this I created a module with a hook where I've been able to retrieve the user information.

function mymodule_form_alter(&$form, $form_state, $form_id)  {
    // retrieve name & surname 
    global $user;
    $user_fields = user_load($user->uid);
    $name = $user_fields->field_user_name['und']['0']['value'];
    $surname = $user_fields->field_user_surname['und']['0']['value'];

    // check the form_id 
    if($form_id=='registration_form'){
        $form['field_new_name']= array('#default_value' => $name);
        $form['field_new_surname']= array('#default_value' => $surname);
        // $form['field_new_name']['#value'] = $name;
        // $form['field_new_name']['widget'][0]['value']['#default_value'] = "joe";
    }
}

I succeed retrieving the data but i fail to set the input to display this value in the input text field...

I also have a select menu to define who is registering :

<select id="edit-who-is-registering" name="who_is_registering" class="form-select required">
    <option value="" selected="selected">- Select -</option>
    <option value="registration_registrant_type_me">Myself</option>
    <option value="registration_registrant_type_user">Other account</option>
    <option value="registration_registrant_type_anon">Other person</option>
</select>

Here I don't know how I can test if the select input has the value "registration_registrant_type_me" in the hook i try to create. Ideally i'd like to hide the name and surname field with the setted value ...

1

There are 1 best solutions below

0
davidvera On

For getting user info :

$user_fields = user_load($user->uid);
$name = $user_fields->field_user_name['und']['0']['value'];
$surname = $user_fields->field_user_name['und']['0']['value'];

then to display the value in the field (i was saved by kint) :

$form['field_new_name']['und'][0]['value']['#default_value'] = $name;
$form['field_new_surname']['und'][0]['value']['#default_value'] = $surname;