2

I have a content type. I have firstname, lastname and email address fields. I need the default value for each field to be the firstname, lastname and email address of the user profile. Also, I need to prevent the user from modifying these values. The user should be able to see the values by default, but the user shouldn't be able to edit them.

1
  • Drupal 6 or 7 ?
    – tostinni
    Aug 10, 2011 at 13:52

2 Answers 2

1

You can create a custom module and add use hook_form_alter to change the default_value of your field and change them to #disabled => true. Here is an example. Don't forget to chage modulename to the name of your module and form-id to the id of your form :-).

function modulename_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form['#id'] == 'form-id') {
        $form['field_name'] = array(
            '#disabled' => TRUE,
            '#default_value' => $user->name
        );
    }
}
10
  • Thanks. How can I get the "id" of the content type?
    – cabita
    Aug 10, 2011 at 14:51
  • You can use dsm($form); (if the devel module is enabled) to check the id. Aug 10, 2011 at 15:05
  • The form ID is already passed as argument to the hook implementation; there is no need to use $form['#id'].
    – apaderno
    Aug 10, 2011 at 15:41
  • I forgot to say that my version of drupal is 6, this code works for drupal 6? I don't know to replacement this: if ($form['#id'] == 'form-id') if the field of profile is profile_first_name, in default_value should be $user->profile_user_name? Thanks.
    – cabita
    Aug 10, 2011 at 15:47
  • This code works for Drupal 6. To know the replacement of form-id you have to run dsm($form['#id']); check the result and replace. if the field of profile is profile_first_name, in default_value should be $user->profile_user_name? if you want the name of the loggedin user use $user->name Aug 10, 2011 at 16:43
0

This code works for me:

function test_form_alter(&$form, &$form_state, $form_id){
global $user;
    if($form_id == 'story_node_form' ){
    if ($user->uid) {
profile_load_profile($user);
        $form['field_first_name'] = array(
            '#type' => 'textfield',
            '#title' => 'First name',
           '#default_value' => $user->profile_first_name,
            '#disabled'=> 'TRUE'            
        );
        $form['#submit'][] = 'test_field_first_name_submit';
    }
     }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.