drupalform-api

Trying to get a dynamic select list using Drupal Forms API


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.


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.'),
    );