Similar questions:
Ajax wrapper replacement on a field widget form
how to create an AJAX field widget
Problem:
Get FIELD_NAME
and DELTA
in AJAX callback function? (See below)
What is done:
Change value of a textfield
in a widget form (see here) upon value change (jQuery event .change()) of another textfield
in widget form.
Code Sample:
in hook_widget_form
:
// Changes of this field fire the AJAX event
$element['value'] = ...
$element['value']['#ajax'] = array(
'callback' => 'some_ajax_callback',
'wrapper' => 'location-div',
'method' => 'replace',
'effect' => 'fade'
);
// This field is updated upon AJAX call
$element['location'] = ...
// Here is where the actual change occurs
if(!empty($form_state['values'][$field['field_name']]['und'][$delta]['value'])) {
$element['location']['#value'] = ...;
}
in some_ajax_callback
:
function some_ajax_callback ($form, $form_state) {
// Where do I get FIELD_NAME, and DELTA?
return $field[FIELD_NAME]['und'][DELTA]['location'];
}
What happens?
As it is mentioned here #default_value
is not populated using AJAX so according to this #value
should be used instead.
The problem is how to get FIELD_NAME
and DELTA
in AJAX callback function? (See above)
UPDATE (NOT WORKING!)
I managed to figure out a workaround to make this work as following:
- Item to be updated receives an ID composed of field_name and delta (e.g.
location-div-myfield-0
(this is necessary if multiple instances of the same field are on the same page) - Save field name (here
myfield
) and delta (here0
) in$field_state
(inhook_field_widget_form
) - Read the saved values from
$field_state
in ajax callback (heresome_ajax_callback
) and return the desired form element.
This however works if there is only one instance of the field in the form, otherwise the values in $form_state
are always those of last instance.
Possible solution
Using the triggering_element
of $form_state
in some_ajax_callback
all necessary info can be derived:
function some_ajax_callback ($form, $form_state)
{
// This contains info about triggering element
// Index 0 = field name, 1 = language, 2 = delta, 3 = element name
$element = $form_state['triggering_element']['#parents'];
$delta = $element[2];
$field_name = $element[0];
...
}