Dominique De Cooman
Published on Dominique De Cooman (https://dominiquedecooman.com)

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

Dominique De Cooman
Thursday, June 10, 2010 - 16:31
form [1]
cck [2]

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 [3] and how the FAPI handles cck fields.


Source URL: https://dominiquedecooman.com/blog/drupal-how-disable-form-element-cck-form-using-form-alter

Links
[1] https://dominiquedecooman.com/blog-topics/form
[2] https://dominiquedecooman.com/blog-topics/cck
[3] http://drupal.org/node/726282