2

I need to add a select field to a form, but I also want the ability to add more values to select field later on. How can I accomplish this in Drupal 7?

I heard (read) some place that you can accomplish something like this with a custom content type? but isn't there any better method to do this?

0

What sort of form?

If it is a node creation form simply add a field of type "term reference" and base your select on a a taxonomy vocabulary.

If it is a custom form then I would still use a taxonomy vocabulary to hold the terms but manually populate the select:

$my_vocabulary_vid = 5;
$terms = taxonomy_get_tree($my_vocabulary_vid);
foreach($terms as $term) {
  $options[$term->tid] = $term->name;
}

$form['select'] = array(
  '#type' => 'select',
  '#title' => t('Selected'),
  '#options' => $options,
);
  • Thanks, Yes it was a node creation form. But "taxonomy vocabulary" seems to make more sense than a custom content type so I'll go with this. – Zubair1 Apr 26 '14 at 10:31
0

As a first step, You can use Select or Other module to collect values from user if not available...

Project page says

Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

As a second step, You need to read this values on hook_node_presave and insert it into select list available options using code like below..

// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);

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