Drupal form option populate from loop

1.5k Views Asked by At

I want to populate select option from loop

$form['vote']['selected'] = array(
 '#type' => 'select',
 '#title' => 'Select',
 '#name' => 'name',
 ); 

 foreach($loop as $row)
 $form['vote']['selected']['#options'] = array($row->id => $row->name);
 }

 return $form;

Need some help?

1

There are 1 best solutions below

0
On BEST ANSWER

This is the standard way to do it:

$options = array();
foreach($loop as $row)
  $options[$row->id] = $row->name;
}

$form['vote']['selected'] = array(
  '#type' => 'select',
  '#title' => 'Select',
  '#name' => 'name',
  '#options' => $options
); 

You might also look at the fetchAllKeyed method of the database query which is a handy shortcut to get data from the database into a keyed array suitable for select lists:

$options = db_query('SELECT id, name FROM {table}')->fetchAllKeyed();

The above will produce exactly the same as the foreach loop above.