Posts Tagged Open Source

Assign attributes to options using FormAPI in Drupal

Drupal FAPI does not support this feature but we can add attributes to options by slightly modifying form.inc file.

You only need to change following line in form.inc file.

<?php
        $options .= '<option value="'. check_plain($key) .'"'. $selected .'>'. 
				check_plain($choice) .'</option>';
	//line no. 1437 of form_select_options() in drupal 6.10
?>

with this

<?php
	$options .= '<option value="'. check_plain($key) .'"'. $selected . 
			drupal_attributes($element['#options_attribute'][$key]) . '>'. 
			check_plain($choice) .'</option>';
?>

You can use like it.

<?php
    $shipping_methods = array('1' => 'Standard Two-Day ($17.00 Total Shipping Price)',
        '2' => 'Priority Overnight ($26.00 Total Shipping Price)',
        '3' => 'FedEx Next Day Delivery $23.95',
        '4' => 'FedEx Next Day Delivery $23.95');
 
    $shipping_method_options = array(
        '1' => array('price' => '17.00', 'class' => 'one'),
        '2' => array('price' => '26.00', 'class' => 'two'),
        '3' => array('price' => '23.95', 'class' => 'three'),
        '4' => array('price' => '23.95', 'class' => 'four'));
 
    $form['default_shipping_method'] = array(
        '#title' => t('Shipping Method'),
        '#type' => 'select',
        '#options' => $shipping_methods,
        '#options_attribute' => $shipping_method_options,
        '#default_value' => variable_get('default_shipping_method', 0),
        '#description' => t('You can change your shipping method from here.'),
    );
?>

, ,

1 Comment