When it comes to fast paced delivery with better managed things nothing beats Content Management Frameworks, yes there are few outs, but the king Drupal 7 still is far better than its counters just because of de-normalized structure of underlying database and best ever flexibility of taxonomies and relations. Last few days for one of our team working on Drupal 7 were really challenging and I really could not managed to not to log our learnings here , so here we go!
Okay, let me first tell what we were expected to do:
Dynamic loading of multiple fields of a form based on selected fields
Having implemented dependent-dropdowns recently, we were aware that D7 respects ajax too much.
We as usual made direction towards Examples Module, we get following code there:
$form['dropdown_first'] = array(
‘#type’ => ‘select’,
‘#title’ => ‘Instrument Type’,
‘#options’ => $options_first,
‘#default_value’ => $selected,
‘#ajax’ => array(
‘callback’ => ‘ajax_example_dependent_dropdown_callback’,
‘wrapper’ => ‘wrap’,
$form['dropdown_second'] = array(
‘#type’ => ‘select’,
‘#title’ => $options_first[$selected],
‘#prefix’ => ‘< div id=”wrap” >’,
‘#suffix’ => ‘< /div >’);
In the above code on selection of dropdown_first, dropdown_second gets values from server via an ajax request and replaces elements inside ‘wrap’. We thought what if we put this wrapper around whole of the form element, we delve for same and a comment on this D7 node turned to be a real catalyst.
We tried following and we were sailing in a short period of time:
//*1 and *2 make form dependent on selected solution area
//*1–define properties for solution area
$form['field_select_a_solution_to_revie']['und']['#ajax'] = array(
‘event’ => ‘autocompleteSelect’,
‘wrapper’ => ‘wrapper-vendor-review’,
‘callback’ => ‘solution_area_selected_ajax_callback’,
‘method’ => ‘replace’,
//*2–define properties for form
$form['#prefix'] = ‘<div id=”wrapper-vendor-review”>’;
$form['#suffix'] = ‘</div>’;
And below is some of the code that we used in solution_area_ajax_callback()
$form_state['rebuild'] = TRUE;
$empty_form = drupal_rebuild_form(‘comment_node_vendor_profile_form’,&$form_state, null );
$empty_form['field_select_a_solution_to_revie']['und']['#value'] = taxonomy_term_load($tid)->name;
This was only a peek how to achieve multi-field dependency in drupal. There are more exciting ways in which FAPI and form-states are proven real powers, depends how we exploit them. As a small bonus, soon going to write on achieving transitive dependency of different fields in drupal forms. Stay tuned !
Our handle on twitter is @sopantech, see you there.