Making fields non-editable in drupal 7

25th Aug 2011

Objective: Want to make some fields (which are computed) non-editable in Drupal 7

1 - How to control the attributes of a field element in drupal 7 D7
the following needs to be done
- add an after_build function for the element

* Implements hook_form_alter().
function msl_po_form_po_line_item_node_form_alter(&$form, &$form_state, $form_id) {
// $form['field_po_li_kg_per_m']['#attributes']['readonly'] = 'readonly'; // does not work
$form['field_po_li_kg_per_m']['und'][0]['#after_build'][] = 'msl_po_li_after_build_element_readonly';
} // end of function msl_po_purchase_order_node_form_alter

* Process after_build for PO Line Items
* Make this element readonly
* #after_build callback for field elements in a form.
function msl_po_li_after_build_element_readonly($element, &$form_state) {
$element['value']['#attributes']['readonly'] = 'readonly';
//$element['value']['#attributes']['disabled'] = 'disabled'; // cannot use this since it'll not be a successful control
return $element;

2 - Should i use disabled or readonly ?
Successful Controls

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

Use only readonly if one wants to make their textfields / texarea non-editable (noneditable, uneditable, read only) please don't make them disabled
since their values will not be submitted to the form.

Blog Categories: 
yashesh.bhatia's picture
Authored By