I'm using Drupal 7 and Form API.

My Problem:

I want to load rows from my Database and put them in a Select Form(Form API). After this form is submitted I want to write the selected option in my database.

The first step works fine but I don't know how to get the selected option for writing it into my database.

Load values from database:

$result = db_select('color', 'c')
->fields('c', array('ID', 'color', 'name')


foreach($result as $row) {
     $options = $row->color . ' ' .$row->name; 

Add options to form:

 $form['colors'] = array(
   '#type' => 'select',
   '#options' => $options,

When form is submited:

db_insert() //Add ID of selected item to database

How do I get the ID of the selected color? The options of this select form is a name combination(color+name)

1 Answer 1


First of all, there is a small error in your code, $options should be an array. Moreover, if you add a key=>value pair for each option, you can get the key of the selected option in the form_submit function. Here is what your foreach could look like:

foreach($result as $row) {
  $options[$row->ID] = $row->color . ' ' .$row->name; 

and in your submit function you can grab the ID of the selected option like this:

$color_id = $form_state['values']['color'];

Good luck!


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.