Read Only Fields for Drupal Forms
When developing CrowdedText.com, I ran into the problem of needing read-only fields once a node had been created. I didn't want to prohibit editing completely. Only for a few fields.
You can't just hide or disable the field, although that's a necessary step. Anyone with a tool like Firebug would still be able to edit the html in real-time and submit the form, changing the value. When some of your backend logic depends on the keeping these values accurate, this is a big no-no.
Let's say you had a "widget_counter" field that tallies us an arbitrary value, and each node has one. You want authors to be able to edit the node, but not the "widget_counter" field.
You will need a custom module that implements hook_form_alter. After determining that you are altering the correct form, add another validation function.
$form['#validate'][] = 'prevent_node_edit';
This function will get called before any of the submission functions. I'm assuming that the field was created with CCK.
function prevent_node_edit($form, &$form_state) {
$form_state['values']['field_widget_counter'][0]['value'] = $form['#node']->field_widget_counter[0]['value'];
}
The $form_state variable is passed to each validation by reference. Anything we change in it will be what is passed to the submission functions for final processing. However, we also get a copy of the $form variable, which just so happens to contain the entire node object of the node that is being edited, all with the original values.
So we just take the value of the widget_counter field in the node object, and put that value in the approriate place in the $form_state variable. No one will ever be able to change the value of that field if they are trying to do it through the normal edit form. The field could still be changed by anyone with direct access to the database, of course.
This is only for one field, but you can include any number of fields you want within the same validation function.
If you would still like users with administration access to edit these fields through the edit form, then you can simply surround the code with an "if" statement.
if (!user_access('administer nodes')) {
//prevent edits
}
More Services
Archive
- July 2011 (1)
- March 2011 (1)
- November 2010 (1)
- July 2010 (2)
- December 2009 (2)

