Last updated July 11, 2014. Created on July 11, 2014.
Edited by er.pushpinderrana. Log in to edit this page.

Sometimes we have requirement to make some form elements in content type or taxonomy read only or disabled. To do this we need a separate module but we can also do this using a small code snippet.

<?php
/*
 * Override form related things using this hook_form_alter.
 * You need to form id to use this code, my module name is 'custom' here.
 * So hook_form_alter is custom_form_alter.
 */


/**
 *
 * Perform alterations before a form is rendered.
 *
 * @param $form
 * @param $form_state
 * @param $form_id
 */
function custom_form_alter(&$form, &$form_state, $form_id) {
 
// Choose your specific form id here, in my case do this for every term and
  // basic page content type.
 
if ($form_id == 'taxonomy_form_term' || $form_id == 'page_node_form') {
   
$form['#after_build'][] = '_after_build_readonly';
  }
}

/**
 * Custom after_build callback handler.
 */
function _after_build_readonly($form, &$form_state) {
 
_disable_components($form);
  return
$form;
}

/**
 * Recursively set the disabled attribute to all
 * basic (html) elements below the given FAPI structure
 * and only to those.
 */
function _disable_components(&$elements) {
  foreach (
element_children($elements) as $key) {
    if (isset(
$elements[$key]) && $elements[$key]) {
     
// Recurse all children
     
_disable_components($elements[$key]);
    }
  }
  if (!isset(
$elements['#type']))
    return;
 
// You may want to extend the list below for your specific purposes.
  // Attribute and value must comply with what the html standard
  // says about the resp. element.
 
switch ($elements['#type']) {
    case
'textfield':
    case
'textarea':
     
$attr = 'readonly';
     
$value = 'readonly';
      break;
    case
'select':
    case
'checkbox':
    case
'file':
     
$attr = 'disabled';
     
$value = 'disabled';
      break;
    default:
      return;
  }
  if (!isset(
$elements['#attributes'])) {
   
$elements['#attributes'] = array();
  }
 
$elements['#attributes'][$attr] = $value;
}
?>

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.