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. #1 by Free css templates - March 31st, 2009 at 19:12

    Really awesome blog. I enjoyed reading this review from you. I found that you really update your site regularly that made me more interesting. I’ve bookmarked your site for my future use.

    Thank you
    sagar

  2. #2 by Drupal master - September 16th, 2010 at 19:28

    You are hacking core!
    You don’t love a kittens.

  3. #3 by vijaycs85 - December 20th, 2011 at 21:59

    I have added a module in my sandbox for this: http://drupal.org/sandbox/vijaycs85/1340952

(will not be published)

 


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.