views:

867

answers:

2

I'm sure this is an easy one for jQuery experts, but I'm a backend guy, and can't find the best way to do this. I have two arrays in Drupal, one is a list of names of views, and the other is an array that contains a list of displays for each view. Here's the code to populate the two arrays:

 //load list of views in to array for select lists
$views = views_get_all_views();
$viewnames = array();
$viewdisplays = array();
foreach ($views as $view) {
  $viewnames[$view->name] = $view->name; 
  foreach ($view->display as $k) {
    $id = $k->id;
    $title = $k->display_title;
    $viewdisplays[$view->name]['id'] = $id;
    $viewdisplays[$view->name]['title'] = $title;
  }
}

Here's the snippet of the form that I'm working with:

$form['view'] = array(
  '#type' => 'select',
  '#title' => t('Select the view to be used for display'),
  '#options' => $viewnames,
);
$form['view_display'] = array(
  '#type' => 'select',
  '#title' => t('Select the display of the gallery view to be used'),
  '#options' => array(),
);

What I want to do, is dynamically fill the view_display select box with the appropriate values. If the user selected "My Favorite View" from the 'view' select, I want to display the $viewdisplays['My Favorite View'] array as the #options to the 'view_display' field.

+1  A: 

It's not a difficult task to do what you ask.

  1. Drupal know what options a select form item has, since it keeps a copy of the form. So you will need to prepopulate the options of the select you want to change with all the options it can have. Also you need to make sure that their values are unique, so you don't get an array like this:

    array(
      1 => 'a-a',
      2 => 'a-b',
      3 => 'a-c',
      4 => 'a-d',
      1 => 'b-a',
      2 => 'b-b',
    )
    
  2. Now you have two options
    1. You send your options for each view to the javascript using
      drupal_add_js($array, 'setting'). This will add the $array to the Drupal.settings variable.
    2. You can get the options through AJAX. In that case you would have to create a menu item with hook_menu.
  3. Now you only need to react on a change in the select for the views, and add their options accordingly, either getting them from an ajax call or the js variable. I would recommend using the variable approach. That could look something like this:

    $("#edit-view").change(function(){
        $("#edit-view_display").html(Drupal.settings.myVariable[$(this).val()]);
    }).change();
    

    You would need to add this js to your form. You could put it in a js file, wrap it in $(document).ready and add it with drupal_add_js

googletorp
A: 

Have you seen the Hierarchial Select module? It's a CCK field type:

http://drupal.org/project/hierarchical_select

Hope this helps!

Collin Klopfenstein