Friday, August 27, 2010

Drupal Multiple Select Form (Two Sides)

Drupal Multiple Select Form (Two Sides)


multiple_select.module
<?php
 /**
  * Implementation of hook_menu()
  */
function multiple_select_menu() {
  $items = array();

  $items['multiple_select'] = array(
    'title' => 'multiple_select',
    'page callback' => 'multiple_select',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['multiple_select_submit'] = array(
    'title' => 'multiple_select',
    'page callback' => 'multiple_select_submit',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function multiple_select() {
  drupal_add_js(drupal_get_path('module', 'multiple_select') .'/multiple_select.js');

  $out = '<form action="/multiple_select_submit" method="POST" id="multiple-select-form">';
    $out .= '<select multiple id="select1" size="10">';
      $out .= '<option value="gan2">gan2</option>';
      $out .= '<option value="gan4">gan4</option>';
      $out .= '<option value="gan5">gan5</option>';
      $out .= '<option value="gan6">gan6</option>';
      $out .= '<option value="gan7">gan7</option>';
    $out .= '</select>';

    $out .= '<select name="option_selected[]" multiple id="select2" size="10">';
      $out .= '<option value="gan1">gan1</option>';
      $out .= '<option value="gan3">gan3</option>';
    $out .= '</select>';

    $out .= '<p>';
    $out .= '<a href="#" id="add"> >> </a> | ';
    $out .= '<a href="#" id="remove"> << </a>';
    $out .= '<p>';

    $out .= '<input type="submit">';
  $out .= '</form>';

  return $out;
}

function multiple_select_submit() {
  echo '<pre>';
  print_r($_POST);
  echo '</pre>';

  return 'hmm';
}
?>

multiple_select.js
Drupal.behaviors.multipleSelectLink = function(context) {
  $('#add').click(function() {
    return !$('#select1 option:selected').remove().appendTo('#select2');
  });

  $('#remove').click(function() {
    return !$('#select2 option:selected').remove().appendTo('#select1');
  });

  // automatically select all options in the second select box before submitting.
  $('#multiple-select-form').submit(function() {
    $('#select2 option').each(function(i) {
      $(this).attr('selected', 'selected');
    });
  });
};

Reference:
http://blog.jeremymartin.name/2008/02/easy-multi-select-transfer-with-jquery.html

No comments: