I have a select field that I would like displaying name from a table that is updated often, so I need the select field to be dynamically made each time you come to this page. My work is SQL is rather recent, so I was wondering if anyone could lend a hand in how to pull the specific field from my table and use it to populate my 'select' item. I've tried to do it a few ways and they have all seem terribly complicated compared to examples I have seen in other modules, I am hoping there is a less complex method. Thanks!

Comments

trevortwining’s picture

If all you are looking for is the SQL, and you're just getting the value from one column, then you can use this SQL statement

SELECT DISTINCT yourfield FROM yourtable ORDER BY yourfield

That will give you a list of all the distinct values in that column, which means that any value, regardless of how many times it appears in that table, will only show up once in your list (which is sometimes helpful for a select field).

If that's not what you need then a bit more detail from you would be helpful.

Trevor Twining
http://www.trevortwining.info

Trevor Twining
Freelance Drupal Dev
Theme/Modules/Sitebuilding

BBlock-1’s picture

That is pretty much what I was looking for, thank you very much. I had a few more steps of sorting a less well made search, this is much simpler and cleaner. Do I need to take the $result from that query and just use mysql_fetch_array to put the seperate items into the #options item in the 'select' array? I've never had anything but a static select until now, sorry for my confusion on this.

~Brian

s3p5’s picture

$options = array("Option1", "Option2", "Etc");

$form['itemname'] = array('#type' => 'select',
                           '#title' => t('Title of Select'),
                           '#options' => $options);
BBlock-1’s picture

Thank you both. The array, plus an iteration function, put all the information perfectly into the select and it changes correctly when items are added to the table. Thanks again.

~Brian

edmund.kwok’s picture

An added note, if you want the value of the select option to be something else, not the title of the option, use an associative array:

$options = ('ops1' => 'Option1', 'ops2' => 'Option2', 'ops3' => 'Option3';
MetraNode’s picture

Good Day,

I am attempting to accomplish the exact same thing for a few days now.
Unfortunately, I have not had much success. Could you please provide a example of the code that I should place in the Allowed Values - PHP Code section. This would be greatly appreciated.

Thank you in advance.

AjK’s picture