Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 - Populate Drop Down select from DB in Form API

I am still new to PHP, and even newer to Drupal's Form API. I'm simply trying to populate a drop down select from the database. I think the issue stems from my lack of a deep understanding of how to work with multidimensional arrays. Any help is sincerely appreciated.

My code is currently:

    //Query DB for Rows
    $query = db_select('hp_education_years');
    $query->fields('hp_education_years', array('id', 'years',));
    $query->orderBy('years', 'ASC');
    $results = $query->execute();

    //define rows
    $options = array();
    foreach ($results as $result) {
        $options[$result->id] = array(
            $result->years,
        );
    }
    $form['education']['year'] = array(
        '#type' => 'select',
        '#title' => t('Year'),
        '#options' => $options,
        '#states' => array(
            'visible' => array(
                ':input[name="data_set"]' => array('value' => 'education'),
            ),
        ),
    );

This returned a populated list, but displays the year's ID in bold as well as the year (2008 for example).

How can I get the dropdown just to display the year, not the year ID in bold, and then the year. It seems like $option is just a level higher than I want it to be? if that makes sense?

Many thanks in advance.

like image 890
Lucas Healy Avatar asked Feb 18 '26 18:02

Lucas Healy


1 Answers

Try changing

//define rows
$options = array();
foreach ($results as $result) {
    $options[$result->id] = array(
        $result->years,
    );
}

to

//define rows
$options = array();
foreach ($results as $result) {
    $options[$result->id] = $result->years;
}

If you look at the example from Drupal's Form API, you'll see that the Options values should be just the string value and not an array.

like image 99
nmc Avatar answered Feb 21 '26 15:02

nmc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!