Drupal Form API and Multiselect Taxonomies

For a recent project, I decided to utilize the Drupal.org module Multiselect to allow a user to select terms from multiple vocabularies in a more user-friendly manner than having to know to CTRL+click or CMD+click items in a multiselect list. Multiselect has a few drawbacks, like not re-ordering items in the list the way they're "supposed to be" when they're de-selected, and as far as I can tell, it doesn't really support groupings (hierachical displays) because of the previous draw back, and probably isn't very useful in an environment where accessibility standards require a screen reader, however, all in all, I found it to be very apt for my case, so I wanted to write a brief description of how I implemented Multiselect in a Drupal 7 environment using the Form API.

Inside the form that I implemented, I wanted users to be able to select a number of terms to include, and a number of terms to exclude. We'll ignore why this was important (and ultimately why it was a mega-PITA to implement) for my project, and just show you how I did it. 

  $form['tabs'] = array(
    '#type'           => 'vertical_tabs',
  );

  $form['itax'] = array(
    '#type'           => 'fieldset',
    '#title'          => t('Required Taxonomy'),
    '#group'          => 'tabs',
  );

  $form['etax'] = array(
    '#type'           => 'fieldset',
    '#title'          => t('Excluded Taxonomy'),
    '#group'          => 'tabs',
  );

  $vocabularies = taxonomy_get_vocabularies();  // Get an array of all vocabs

  $termsoptions = array();

  foreach ($vocabularies as $vocab) {
    $terms = taxonomy_get_tree($vocab->vid, 0);  // Pull an array of terms for each vocabulary

    foreach ($terms as $term) {
      $termsoptions[$vocab->vid][$term->tid] = $term->name; // Build the termsoption array
    }

    $form['itax']['includeterms_'.$vocab->vid] = array(
      '#type'           => 'multiselect',
      '#title'          => t('Require Taxonomy Terms from ') .$vocab->name,
      '#options'        => $termsoptions[$vocab->vid],
      '#multiple'       => TRUE,
      '#size'           => 10,
      '#default_value'  => 'includeterms_'. $vocab->vid, // You should pull your saved values here.
    );

    $form['etax']['excludeterms_'.$vocab->vid] = array(
      '#type'           => 'multiselect',
      '#title'          => t('Exclude Taxonomy Terms from ').$vocab->name,
      '#options'        => $termsoptions[$vocab->vid],
      '#multiple'       => TRUE,
      '#size'           => 10,
      '#default_value'  => 'excludeterms_'. $vocab->vid, // You should pull your saved values here.
   );

  }

This made selecting terms to include and exclude very easy. Using vertical tabs allowed me to separate out include and exclude taxonomies into separate tabs, since each set of choosers is relatively large and with as few as two vocabularies, quickly becomes visually overwhelming.