1

I work with drupal 7. In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?

 $form['officers']['officer'] = array( 
'#title' => t('Select the officer'), 
'#type' => 'select', 
'#description' => t('Please, select the officer'), 
'#options' => players(), 
'#multiple' => FALSE, 
'#empty_value' => ' ',
'#empty_option' => '- None -',  

);

For example in the "Text Field" there is property #autocomplete which defines a path where Drupal’s automatically included JavaScript will send HTTP requests using jQuery.

 $form['team_name'] = array( 
'#title' => t('Name'), 
'#type' => 'textfield', 
'#description' => t('Please, insert your name'), 
'#autocomplete_path' => 'autofillform/teamname' ,

);

And i created the module which handles it.

<?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(  
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',  
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  } 
 print drupal_json_encode($matches);
 return; 
 }

Are there any possibility to do the same with "Select" ?

1 Answer 1

1

You need to focus on #ajax option. That will look like

$form['officers']['officer'] = array( 
  '#title' => t('Select the officer'), 
  '#type' => 'select', 
  '#description' => t('Please, select the officer'), 
  '#options' => array(), 
  '#multiple' => FALSE, 
  '#empty_value' => ' ',
  '#prefix' => '<div id="officer-wrapper">',
  '#suffix' => '</div>'
  '#empty_option' => '- None -',  
  '#ajax' => array(
     'callback' => 'path/to/callback/handler',
     'wrapper' => 'officer-wrapper',
     'method' => 'replace',
     'effect' => 'fade',
  ),
);

In the submit handler you will have change the form element for #options and render to post back using drupal_json_output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.