CCK form field changes using Drupal's hook_form_alter don't work? Use #after_build

I ran into issues when trying to use drupal's hook_form_alter to change some attributes of cck fields in a node form. It appears that depending on the weight of the module the form_alter is in, it might get called before the actual form element has been processed.

To make sure, you can set a function to be called after the form has been properly created, but before rendering.

In your form alter, add the after build key to the form field's array:

$form['field_course_status']['#after_build'][] = 'course_disable_status_field';

Then in your custom function make your changes. You should do a print_r($form_element) or the devel module's dpm($form_element) function to see what the element looks like - I had to put my change into the $form_element['value'] array and not the $form_element itself.

 * Make certain fields in the course form read only
 *
 */
function course_disable_status_field($form_element, &$form_state) {
  $form_element['value']['#attributes'] = array('disabled' => 'disabled');
  return $form_element;
}

 For reference see:

  • http://drupal.org/node/726282
  • http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6#after_build
  • http://benbuckman.net/tech/10/07/customizing-drupal-date-field-hookformalter-and-afterbuild
  • http://drupal.org/node/336355#comment-1115987
  • http://drupal.org/node/381458#comment-2179742
  • http://drupal.org/node/174575
Tags