• 12gen
    Categories: Programming Commenti disabilitati

    Field definition. Here are the form field definitions; in this case they are inserted in a form alter hook.
    UPDATE 2010/2/16: Note that every combobox is linked onblur with the next one and on focus with the previous one.
    UPDATE 2010/4/12: Download the source code .

    1. function module_form_alter(&$form, $form_state, $form_id) {
    2. if($form_id == "target_form_id") {
    3. $form['field_parent']=array(
    4. '#type' => 'textfield',
    5. '#title' => t('Parent'),
    6. '#autocomplete_path' => 'autocomplete/parent',
    7. '#attributes' => array('onblur' => 'parentSelected($(this));')
    8. );
    9.  
    10. $form['field_child']=array(
    11. '#type' => 'textfield',
    12. '#title' => t('Child'),
    13. '#autocomplete_path' => 'autocomplete/child',
    14. '#attributes' => array('onfocus' => 'parentSelected($("#edit-field-parent"));'),
    15. );
    16. }
    17. }

    Client side script. When a value for the parent textfield is selected, the available values for the child textfield are restricted in a range (this is why they are linked, right). This is done altering the autocomplete path of the child

    1. function parentSelected(parent) {
    2. // Get the url from the child autocomplete hidden form element
    3. var url = $("#edit-field-child-autocomplete").val();
    4. // Alter it according to parent value
    5. url = url.replace(/\?q=autocomplete(.*)/, "?q=autocomplete/child")+"/"+parent.val();
    6. // Recreate autocomplete behaviour for the child textfield
    7. var input = $('#edit-field-child').attr('autocomplete', 'OFF')[0];
    8. recreateAutoComplete(input, url);
    9. }
    10.  
    11. function recreateAutoComplete(input, url) {
    12. $(input).unbind();
    13. var acdb = new Drupal.ACDB(url);
    14. $(input.form).submit(Drupal.autocompleteSubmit);
    15. new Drupal.jsAC(input, acdb);
    16. }

    The menu hook. The parent textfield is defined like a normal autocomplete callback, while the child's one accept a parameter from the url.

    1. function module_menu(){
    2. $items['autocomplete/parent'] = array(
    3. 'title' => 'Parent textfield autocomplete',
    4. 'page callback' => 'module_autocomp_parent',
    5. 'access callback' => TRUE,
    6. 'access arguments' => array('access content'),
    7. 'type' => MENU_CALLBACK
    8. );
    9.  
    10. $items['autocomplete/child'] = array(
    11. 'title' => 'Child textfield autocomplete',
    12. 'page callback' => 'module_autocomp_child',
    13. 'page arguments' => array(2,3),
    14. 'access callback' => TRUE,
    15. 'access arguments' => array('access content'),
    16. 'type' => MENU_CALLBACK
    17. );
    18. }

    Autocomplete callback. The autocomplete callback for the child is enabled to receive as first parameter the value specified in the parent textfield

    1. function module_autocomp_child($parentValue, $childValue) {
    2. }