Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Hello,
I'm hoping somebody could help me with this. I want to pre-populate and hide a userreference if a parameter is passed in the through a url. E.g.
node/add/lesson?person=5
My solution so far is to set the default value and hide the field using CSS.
<?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
if(is_numeric($_GET['person'])){
$person = user_load(array('uid'=>$_GET['person']));
if($teacher->uid){
$form['field_person']['#prefix'] = '<div class="form-item"><label>Person:</label> '.$person->name.'</div><div style="display:none">';
$form['field_person']['#suffix'] = '</div>';
$form['field_person'][0]['#value'] =$person->uid;
$form['field_person'][0]['#default_value'] =$person->uid;
$form['field_person']['#default_value'][0]['uid'] =$person->uid;
}
}
}
?>
This works fine (so maybe this will help some people), but is there any way I can set the type of the field to 'hidden'? When I tried it using
<?php
$form['field_person'][0]['#type'] ='hidden';
?>
it didn't do anything. Although I should add that I'm using a view to also add the possible options.
Any pointers would be much appreciated.
Comments
Comment #1
russellb CreditAttribution: russellb commentedI've been looking at pre-populating and hiding fields too. It looks to me like prepopulate doesn't work with hidden fields.
Comment #2
xanderol CreditAttribution: xanderol commentedUnfortunately when you hide the field it prevents the Pre-populate module from setting the value of the field.
If you are trying to make sure the field can't be changed once it is set with prepopulate you can disable the field.
In Drupal 7 you can use
$form['field_fieldname']['und']['#disabled'] = true;
But I'm not sure if that format will work with Drupal 6.
Comment #3
fehin CreditAttribution: fehin commentedHi xanderol, where does the code go?
Comment #4
xanderol CreditAttribution: xanderol commentedYou have to create a custom module which calls hook_form_alter like the one in the original post.
Comment #5
fehin CreditAttribution: fehin commentedThanks. I used $form['field_fieldname']['#disabled'] = true; in my template.php and it worked.