Back to top

Use Drupal Form API to disable one of the items in an #options array()

For Drupal elements like checkboxes or radios we provide the options for these lists via a array which as per Drupal docs has to be a simple key value pair.

For the element checkboxes or radios, if you do #disabled, it will disable all the items from the options array(). 

What if you want to disable only one of the checkboxes or have a class on ony one of the radio element ?? Javascript ? or a crude element_process() ?

There is actually a a very neat and clean way (and largely undocumented it seems),

<?php $form['myboxes'] = array( '#type' => 'checkboxes', '#options' => array( 'foo' => t('Foo'), 'bar' => t('Bar'), 'baz' => t('Baz'), ), ); $form['myboxes']['foo'] = array( '#attributes' => array('class' => array('ok')), ); $form['myboxes']['bar'] = array( '#disabled' => TRUE, ); ?>



on 22 Oct 2014 by
Swarad Mokal
Solutions Architect, Sr. Drupal Developer, Team Lead

All men dream but not equally. Those who dream by night in the dusty recesses of their minds wake in the day to find that it was vanity; but the dreamers of the day are dangerous men, for they may act their dream with open eyes to make it possible.