How can I alter the key/value items of a checkboxes component in a webform?
I've followed this answer and I successfully altered a select list component for both render and submission.
I'm trying to do the same with a multiple choice component, but although the form is rendered correctly, the values are not saved on submission.
This is my code:
function my_form_webform_client_form_30_alter (&$form, &$form_state) {
$form = mycustom_form($form);
}
function mycustom_form($form){
$form['#validate'][] = 'mycustom_webform_validate_form';
$form['#submit'][] = 'mycustom_webform_submit';
dpm($form['submitted']['code']['#options']); // ('0'=>'a value', '1'=>'another value');
$codes = array('foo', 'bar');
foreach ($codes as $key => $value) {
$form['submitted']['code']['#options'][$value] = $value;
}
return $form;
}
function mycustom_webform_validate_form($form, &$form_state) {
dpm($form_state['values']['submitted']);
// selecting all checkboxes I get all the four values
}
function mycustom_webform_submit($form, &$form_state) {
drupal_set_message('<pre>' . print_r($form_state, true) . '</pre>');
// only 'a value' and 'another value' are submitted
}
UPDATE
I even tried to add some values to the initial form and manipulate them programmatically.
The submission result is like no manipulation was done.
I update my code for a better explanation.
UPDATE 2
I've tried dumping the submitting form.
I updated my code with the results.
UPDATE 3
I confirm that removing the "Multiple" flag from the component, causes the issue to be fixed.
Unfortunately I need a multiple answer, so I can't remove it.
UPDATE 4
This is another solution I'm trying, using hook_webform_select_options_info():
function mycustom_webform_select_options_info() {
$items = array();
if (function_exists('_mycustom_users_options')) {
$items['code'] = array(
'title' => t('User codes'),
'options callback' => '_mycustom_users_options',
);
}
return $items;
}
function _mycustom_users_options() {
$output = array();
$codes = mycustom_user_codes(); // <- these values are based on logged user
foreach ($codes as $key => $value) {
$output[$value] = $value;
}
return $output;
}
function mycustom_user_codes() {
$result = // a db query based on user id;
while($usercode = db_result($result)){
$output[] = $usercode;
}
return $output; // array({[0] => 'a value', [1] =>'another value'})
}
mycustom_webform_validate_form ()
twice? Also, $form is passed by reference as a function argument in validate and submit handlers, i.e._submit(&$form, &$form_state)
. Let me know, and if you've skipped some code please post it – I think I can help you figure this out.