Question

So Drupal Forms API has options for generating a select box.

However, the example contains static information. I would like to generate a dynamic select list, in the "Drupal" way.

Here's the code example:

   $form['selected'] = array(
   '#type' => 'select',
   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No'),
     1 => t('Yes'),
   ),
   '#default_value' => $category['selected'],
   '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
   );

I want the array under #options to become dynamic - should I just generate something before this beforehand, pass it to a variable and put it into the array? I'm not quite sure how I can preserve the structure of this code, and insert a way for a dynamic solution.

Was it helpful?

Solution

Yes, you need to generate your options array dynamically before the $form['selected'] array definition like this:

$myOptionsArray = myOptionsCallback($param1, $param2);
$form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => $myOptionsArray,
    '#default_value' => $category['selected'],
    '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
);

OTHER TIPS

You can do it like this:

'#options' => custom_function_for_options($key)

and then define custom_function_for_options() like this:

function custom_function_for_options($key){
$options = array(
    'Key Value 1' => array(
        'red' => 'Red',
        'green' => 'Green',
        'blue' => 'Blue'
    ),
    'Key Value 2' => array(
        'paris' => 'Paris, France',
        'tokyo' => 'Tokyo, Japan',
        'newyork' => 'New York, US'
    ),
    'Key Value 3' => array(
        'dog' => 'Dog',
        'cat' => 'Cat',
        'bird' => 'Bird'
    ),
);

    return $options;

}

The $key is on the basis of which $options will return a set of values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top