I have a form in Drupal 7 that generates Radio Buttons from a custom function. On submit I take the index value of the selected button and process it thru another custom function. My problem is that if the first radio button is chosen the index ($form_state['values']['stores']) is not generated. I suppose I could just hard-code the first button to the first result in the corresponding array but I'd really like to figure out why this is happening.
Here's my code:
Form:
hook_form {
global $user;
$user_fields = user_load($user->uid);
$zipcode = $user_fields->zip_code['und']['0']['value'];
$defaults = !empty($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $zipcode;
$storename = getmystorename($defaults);
$form['zip_code'] = array(
'#title' => t('Zip Code'),
'#type' => 'textfield',
'#required' => TRUE,
'#default_value' => $defaults,
'#ajax' => array(
// #ajax has two required keys: callback and wrapper.
// 'callback' is a function that will be called when this element changes.
'callback' => 'settings_form_callback',
'wrapper' => 'textfields',
),
);
if(count($storename) > 0) {
$form['textfields'] = array(
'#prefix' => '<div id="textfields">',
'#suffix' => '</div>',
'#type' => 'fieldset' );
$form['textfields']['stores'] = array(
'#type' => 'radios',
'#title' => t('Choose your store:'),
'#options' => $storename,
'#default_value' => $storename[0], );
} else {
$form['textfields']['incorrect'] = array(
'#title' => t('Sorry, there are no stores available near you.'),
'#type' => 'fieldset', );
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
}
Submit:
hook_form_submit {
$zipcode = $form_state['values']['zip_code'];
//Check that results were given for the zip code
if(!empty($form_state['values']['stores'])) {
$linkposition = $form_state['values']['stores']; }
//If results were given grab the store link
//if(isset($linkposition)) {
//querypath the array of the store name to grab link
$mystorelinks = getmystorelink($zipcode);
$storelink = $mystorelinks[$linkposition];
}
Generated arrays:
Array ( [0] => Store1 [1] => Store2 [2] => Store3 [3] => Store4 [4] => Store5 [5] => Store6 [6] => Store7 [7] => Store8 [8] => Store9 [9] => Store10 )
Array ( [0] => http://www.example.com/stores/store1.html [1] => http://www.example.com/stores/store2.html [2] => http://www.example.com/stores/store3.html [3] => http://www.example.com/stores/store4.html [4] => http://www.example.com/stores/store5.html [5] => http://www.example.com/stores/store6.html [6] => http://www.example.com/stores/store7.html [7] => http://www.example.com/stores/store8.html [8] => http://www.example.com/stores/store9.html [9] => http://www.example.com/stores/store10.html )