Drupal how to disable a form element in a cck form using form alter

Posted by: 
Dominique De Cooman

The standard way of altering form elements and setting them disabled does not work with cck fields.

<?php
function my_module_form_alter(&$form, &$form_state$form_id) {
  
$form['my_element']['#disabled'] = true
}
?>

The FAPI process handler of the CCK field won't transfer the #disabled attribute to its children elements.
You'll need this snippet to make it work.
<?php
/**
 * implementing hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state$form_id) {
  if (
$form_id == 'some_node_form') {
    
$form['#after_build'][] = '_my_module_after_build';        
  }
}

/**
* Custom after_build callback handler.
*/
function _my_module_after_build($form, &$form_state) {
  
// Use this one if the field is placed inside a fieldgroup.
  
_my_module_fix_disabled($form['some_group']['field_some_field']);
  
  
//When using a field
  //_my_module_fix_disabled($form['field_some_field'];  
  
  
return $form;
}

/**
* Recursively set the disabled attribute of a CCK field
* and all its dependent FAPI elements.
*/
function _my_module_fix_disabled(&$elements) {
  foreach (
element_children($elements) as $key) {
    if (isset(
$elements[$key]) && $elements[$key]) {

      
// Recurse through all children elements.
      
_my_module_fix_disabled($elements[$key]);
    }
  }

  if (!isset(
$elements['#attributes'])) {
    
$elements['#attributes'] = array();
  }
  
$elements['#attributes']['disabled'] = 'disabled';
}
?>

EDIT:
Some useful related stuff. Explains why a hook form alter wont work http://drupal.org/node/726282 and how the FAPI handles cck fields.

Comments

Drupal how to disable a form element in a cck form using form alter

First off, thank you for this code. Worked great for disabling.

However, I have my cck fields set to a default value. And when I used this snippet, the default values were erased once I clicked the save button. Is there any lines i could add to this to have it save the default values that I had set in drupal?

Thanks again for your help.

Milan

Drupal how to disable a form element in a cck form using form alter

I believe when a form field is disabled no values are submitted, this is rather a html related issue than a form api/drupal related issue http://stackoverflow.com/questions/1191113/disable-select-form-field-but...

Drupal how to disable a form element in a cck form using form alter

Well that makes sense. Thank you for the response, Dominique!

Drupal how to disable a form element in a cck form using form alter

replace $elements['#attributes']['disabled'] = 'disabled' with this $elements['#attributes']['readonly'] = 'readonly' to save default value.

Add new comment