Module Development: Disabled vs. Readonly Form Fields

Published May 28, 2009

One of the attributes that you can set for any form element using Drupal's FormAPI is "#disabled". This effectively disables the form element - in most browsers, the user actually sees the element "greyed out" and is unable to set focus on the element.

When a form element is disabled, there is the sometimes unintended consequence of the data from that field not being sent back to the server when the form is submitted. For forms that were initially blank (like new node forms, for example), this usually isn't a problem. But for "edit" forms, this can be a dealbreaker - this problem sometimes shows it's ugly head when a developer tries to use the "#disabled" attribute to add an additional layer of security to the form - forcing the user to click an "edit" link that users jQuery to un-disabled the form field.

A better solution to utilize when you want this extra layer of "are you sure"-type security is to utilize the "readonly" HTML attribute. Like "disabled", "readonly" makes the field uneditable, but unlike "disabled", the values are passed back to the server when the form is submitted. Unfortunately, there is no Drupal-equivalent, so to implement it, you'll need to do something like this:

$form['my_textfield']= array(
'#type' => 'textfield',
'#title' => t('my textfield'),
'#size' => 20,
'#attributes' => array('readonly' => 'readonly'),
);

Comments

the problem with simply setting to readonly is that anyone with a tool like firebug can still edit the "read only" field.

a more secure way to do this is to set the #type to 'value' in which case it is still posted but is not editable - problem with this one is that it isn't visible either.

sadly, the most complete solution is a bit cludgy - take the value and make it a markup or other field which is by definition not editable just to show the value; and also include the original field set to type value.

not exactly sure why #disabled couldn't just do the right thing??

Submitted by Guest (not verified) on Fri, 06/19/2009 - 04:06

at least for Drupal6, i thnik the correct way to do this is to set both the #value and the #default_value and then set #disabled = true.

#value will get posted and the default value will show in textfield but be greyed out.

Submitted by Guest (not verified) on Fri, 06/19/2009 - 04:28

Thanks for this tip, exactly what I needed. I set both the value and default value as well as setting it to readonly.

Submitted by Guest (not verified) on Wed, 06/15/2011 - 10:30

'#attributes' => array('readonly' => 'readonly'),
only for this line i suffer 2 or 3 hour on net.

thanks

Submitted by Guest (not verified) on Sat, 02/04/2012 - 06:17

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name
CAPTCHA