I wanted to add values to a select list dynamically. Another module generates an array from a web service and I want to use those values to populate a select list in a form using hook_form_alter.
I tried directly adding the options in #options of the field using the following code
<?php $form['field_mage_category']['und']['#options']=$arr; ?>
The above code adds the options to the select list and returns a value according to the options selected but when the form is loaded again for editing. The option is set to default value and other issue is that when a single option is deleted. The respective value is not getting deleted from the field_data table.
I tried using #after-build property to populate the select list.below code is the call to _add_category_select_list function
<?php function main_menu_form_alter(&$form, &$form_state, $form_id){
if($form_id=='main_menu_node_form'){
form['field_mage_category']['#after_build'] = array('_add_category_select_list');
} ?>
and following is the code in the _add_category_select_list function
<?php function _add_category_select_list($element, &$form_state) {
$mlib=new Mlibrary();
$main_category=$mlib->get_main_menu_Categories();
foreach($main_category as $main){
$element['und']['#options'] = array($main['category_id'] => $main['Title'])+ $element['und']['#options'];
}
return ($element);
} ?>
The above code populates the select list but when the option is selected it is not returning any values for the options selected. Can anyone give me a proper way to add #options to select list dynamically using hook_form_alter or any other options that will allow me to add options from my module.