Thursday, January 12, 2012

How add Data Base Values in selection box(drop-down list ) on Webform Drupal ?

While I implementing MLM (Multi-Level Marketing) Software in drupal, I am forced to do a registration form,  that contains Country Selection Box. Whole Countries are stored in a database and we have to load these values to the selection box. The forms in drupal are created using Webform module. I personally like the webfrom module, because we can create/edit any form within seconds by using the GUI. 

 At first I create a Webform component of type select options. In the configuration section, you can see a drop-down list "Load a pre-built option list:"

that is the value is loading through code. I will explain in detail, for loading the values from Database we have to implement a hook hook_webform_select_options_info() in any of modules (Here I am assuming that you know hoe to create modules in drupal, if not please refer Drupal documentation). 

Refer below code to complete module details:

function country_webform_select_options_info() {
  $items = array();
  $items['countries'] = array(
    'title' => t('Countries'),
    'options callback' => 'as_webform_options_countries',
  );

  return $items;
}

/**
 * Webform options info callback. Just give some countries as example
 */
function as_webform_options_countries() {
  $countries = array(
    t('Europe') => array (
      'nl' =>  t('The Netherlands'),
      'be' =>  t('Belgium'),
      'fr' =>  t('France'),
    ),
    t('Africa') => array (
      'tu'  =>  t('Tunisia'),
      'sa'  =>  t('South Africe'),
    ),
    t('Asia') => array (
      'ru'  =>  t('Russia'),
      'cn'  =>  t('China'),
    ),
    'key' => t('some country that is in no group'),
  ); 
 
/**
 *  This is Actual database values
 */
 $countries = array();
 $sql = "SELECT *
   FROM infinie_mlm_country";
  
 $result = db_query($sql);
 while ($row = db_fetch_object($result)) {
 $countries[$row->id] = $row->country_name;
 }
  
  return $countries;
}

After enabling this module, you can see the title in  "Load a pre-built option list:". Select these values to appropriate Webform components will leads to display whatever we coded.