I'm trying to create a custom widget for my module which will contain a textfield to hold a question(textfield), Question style (select box), potential answers (typed into textarea).
I'd then like an "add another item" button so the client can add as many questions as they like.
I've got a basic ajax widget working but i'm not sure if I've constructed it correctly because when I want to validate the data in hook_field_validate I don't seem to be able to access each question seperately.
I thought i'd be able to validate each question before the next is added by ajax but this doesn't seem to be working.
Asssuming this code (below) is correct, can you please advise how I can validate each time the "add another item" is clicked.
My hook_field_widget_form looks like this:
function keep_warm_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$element['question_wrapper'] = array(
'#type' => 'fieldset',
'#title' => t('Questions'),
// Set up the wrapper so that AJAX will be able to replace the fieldset.
'#prefix' => '<div id="names-fieldset-wrapper">',
'#suffix' => '</div>',
);
if (empty($form_state['num_names'])) {
$form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
//other form elements
$element['question_wrapper'][$i]['question'] = array(
'#type' => 'textfield',
'#title' => t('Question number '. $form_state['num_names']),
);
}
$element['question_wrapper']['add_question'] = array(
'#type' => 'submit',
'#value' => t('Add another question'),
'#submit' => array('ajax_example_add_more_add_one'),
// See the examples in ajax_example.module for more details on the
// properties of #ajax.
'#ajax' => array(
'callback' => 'ajax_example_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
$element['question_wrapper']['remove_name'] = array(
'#type' => 'submit',
'#value' => t('Remove one'),
'#submit' => array('ajax_example_add_more_remove_one'),
'#ajax' => array(
'callback' => 'ajax_example_add_more_callback',
'wrapper' => 'names-fieldset-wrapper',
),
);
}
return $element;
}
And my ajax callback
function ajax_example_add_more_callback($form, $form_state) {
$form_state['num_names']++;
return $form['field_question'];
}