1

I'm working on a custom module and I'm adding a form that uses checkboxes. All is fine with using code like:

$form['tags'] = array( '#type' => 'checkboxes', '#options' => array( 88 => 'option1', 100 => 'option 2', 79 => 'etc' ), '#title' => t('Tag this project as...'), );

The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy). I do not want to use an autocomplete, I want to use checkboxes.

Specifically, how do I get the results from the database and format into a proper array for the options array? Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value?

All of the examples I've seen are extremely basic and never show how to do this from a database call. Thanks for reading/answering

1

To populate your options array with data from table my_table, with value keys from column value and text from column atext, you can use:

$options = array();
$result = db_select('my_table', 'mt')
            ->fields('mt', array('value', 'atext'))
            ->execute();
foreach ($result as $row) {
  $options[$row->value] = $row->atext;
}

To get taxonomy terms, you could use the code above to query tid and name from the taxonomy_term_data table (plus add a condition() for the vocabulary id), but for this specific usage you'd better to use the right API:

$options = array();
// Get term tree for vocabulary which id is in $vid.
$terms = taxonomy_get_tree($vid);
foreach ($terms as $term) {
  $options[$term->tid] = $term->name;
}

Just do not forget that vocabularies are tree structures. See the documentation for the taxonomy_get_tree() API to know how to limit the terms you want to get from a vocabulary wrt starting term and tree depth.

  • Thanks much for the great explanation! Very helpful. Sometimes it's very hard to know where to look in the documentation and for which api. – user924011 Jul 14 '15 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.