echmultiselect

Simple Wrapper Widget for the jQuery UI MultiSelect Widget by Eric Hynds
25 followers

This is a simple Wrapper Widget for the jQuery UI MultiSelect Widget by Eric Hynds.
Details about the widget can be found here.
A Demo of the JQuery widget can be found here.

Requirements

Tested with Yii 1.1.8.

Unpack the widget

Extract the contents of the zip file directly into the protected/extensions/ folder of your Yii application.

Use the widget

1. Basic Use with model and dropDownAttribute

Now you can use the widget in your view file, for example like this:

$data= CHtml::listData(Color::model()->findAll(), 'ID', 'Name');
$this->widget('ext.EchMultiselect.EchMultiselect', array(
    'model' => $model,
    'dropDownAttribute' => 'color',     
    'data' => $data,
    'dropDownHtmlOptions'=> array(
        'style'=>'width:378px;',
    ),
));

This Yii widget creates a 'drop down list' with the given data and applies the JQuery widget to it, which turns the ordinary HTML select control into an elegant MultiSelect list of checkboxes with themeroller support.

To avoid confusion: I refer to the initial select element (that is subsequently hidden) as the 'drop down list'; and to the eventual input element created by the JQuery Widget as the 'MultiSelect list'.

The provided 'dropDownHtmlOptions' will be adopted by the MultiSelect list. If you for example provide a style for the drop down list, it will also applied to the resulting MiltiSelect list.

The drop down list will be hidden directly after it is created: I placed a Javascript code to hide the element directly after it, to prevent it from being displayed while the page is loading, only to be hidden after the page has been loaded (as suggested here). I truly dislike that appearing/disappearing on page load, so I didn'd wait for the MultiSelect widget to hide the drop down list.

Note: You could also hide the drop down list by adding the style display:none to the dropDownHtmlOptions. But hiding it via JS-Code provides backward compatibility: if the user has JS disabled, multiselect will not work, but the original select element will stay visible.

2. Basic Use with name and value

$colors = array('red','yellow','orange','black','green','blue');
$this->widget('ext.EchMultiselect.EchMultiselect', array(
    'name'=>'colors[]',
    'data'=>$colors,
    'value'=>array(0,3),
    'dropDownHtmlOptions'=> array(
        'class'=>'span-10',
        'id'=>'colors',
    )
));

Here, name is the name of the drop down list. This must be set if model and dropDownAttribute are not set.
value contains the pre-selected input value(s). In this case, 'red' and 'yellow' will be pre-selected by default. value is used only if model is not set.
If you select red, green, blue and submit, $_POST['colors'] will be an array containing the selected values, like: Array([0] => 0,[1] => 4, [2] => 5).

If model and dropDownAttribute are specified, they are used to generate the name and id of the drop down list. Note that if name is specified in addition, it overrides the automatically generated name. Similarly, if id is specified in the dropDownHtmlOptions, it overrides the generated id.

3. Use as a filter in CGridView

The following example was provided by jeremy (see comments)

$this->widget('zii.widgets.grid.CGridView', array(
    ....
    'columns' => array (
        'firstColumn',
        'secondColumn',
        // use EchMultiselect for the next column
        array (
            'name'=>'thirdColumn',
            'filter'=> $this->widget('ext.EchMultiselect.EchMultiselect', array(
                'model' => $model,
                'dropDownAttribute' => 'thirdColumn',
                'data' => $colors,
                'options' => array('buttonWidth' => 80, 'ajaxRefresh' => true),
            ),
            true // capture output; needed so the widget displays inside the grid
        ),
    ),
));

By setting 'ajaxRefresh'=>true, we indicate that the widget should be 'refreshed' after every ajax request that occurs on the current page.

4. Overriding default options and filterOptions

You can provide optional parameters for the JQuery widget, if you want to change their default settings. Here's an example:

$data= CHtml::listData(Color::model()->findAll(), 'ID', 'Name');
$this->widget('ext.EchMultiselect.EchMultiselect', array(
    'model' => $model,
    'dropDownAttribute' => 'color',     
    'data' => $data,    
    'dropDownHtmlOptions'=> array(
        'style'=>'width:378px;',
    ),
    'options' => array( 
        'header'=> Yii::t('EchMultiSelect.EchMultiSelect','Choose an Option!'),
        'minWidth'=>350,
        'position'=>array('my'=>'left bottom', 'at'=>'left top'),
        'filter'=>true,
    ),
    'filterOptions'=> array(
        'width'=>150,
    ),
));

Now the default “check all”, “uncheck all”, and “close” links in the header will be replaced with the specified text 'Choose an Option!, the widget will have a minimum width of 350px (instead of the default 225px), and the filter plugin will be applied.

Details about the available 'options' and 'filterOptions' for the jQuery UI MultiSelect Widget can be found on the Project page. Here's a list of the options and their default values for quick reference:

// 'options':
'header'=> true,
'height'=>175,
'minWidth'=>225,
'position'=>'',
'checkAllText' => Yii::t('EchMultiSelect.EchMultiSelect','Check all'),
'uncheckAllText' => Yii::t('EchMultiSelect.EchMultiSelect','Uncheck all'),
'selectedText' =>Yii::t('EchMultiSelect.EchMultiSelect','# selected'),
'selectedList'=>false,
'show'=>'',
'hide'=>'',
'autoOpen'=>false,
'noneSelectedText'=>'-- ' . Yii::t('EchMultiSelect.EchMultiSelect','Select Options') . ' --',
'multiple'=>true,
'classes'=>'',
'filter'=>false,
// 'filterOptions':
'label' => Yii::t('EchMultiSelect.EchMultiSelect','Filter:'),
'width'=>100,
'placeholder'=>Yii::t('EchMultiSelect.EchMultiSelect','Enter keywords'),
'autoReset'=>false,

The filter plugin is disabled by default. To enable it, you have to set the filter attribute to true. The filterOptions will have no effect, if filter is set to false, i.e. the filter plugin is disabled.

Note that the default options are already translated with Yii::t() where necessary.

For details about the position option see the jQuery page for the Position utility. The default position of the Multiselect list array('my'=>'left top', 'at'=>'left bottom').

5. import widgets in config file to simplify calls

As an alternative, you can import the path of your widgets in your config file
protected/config/main.php:

'import'=>array(
    ...
    'ext.EchMultiselect.*',
    ...
),

Note that ext is short for application.extensions. Now you can call this widget (and any other widgets you may have placed under extensions/widgets/ ) with only its name, without specifying its path, i.e. like this:

$this->widget('EchMultiselect',...);

Changes

  • Dec 17, 2012 (v1.3)
    • Added the changes suggested by jeremy in the comments, to make this widget work as a 'filter' in CGridView (added the ajaxRefresh and buttonWidth options). Thanks to jeremy for providing the code!
    • Added translation files. You can add your own translations to the folder EchMultiSelect/messages.
  • Mar 12, 2012 (v1.2)
    • Zipped the Widget-files directly, without putting them into an additional EchMultiSelect directory. That is: only directory structure changed. No changes in the code! (Reason of the change: The contents of the zip file are often extracted directly into the extensions directory, which resulted in the need to call the widget with $this->widget('ext.widgets.EchMultiselect.EchMultiselect', array(...);)
  • Feb 06, 2012 (v1.1)
    • Added the ability to pass options to the MultiSelect Filter Widget via parameter 'filterOptions' (thanks to sucotronic for pointing this out in the forum).
    • Made sure 'multiple' attribute of drop down list is set to 'true', even if not explicitly set in 'dropDownHtmlOptions' (only if 'multiple'=>true in 'options' of course).
    • Fixed a bug regarding the 'name' parameter

Note for versions v1.1 and v1.0

  • If you extract these versions directly into the protected/extensions/widgets/ directory, the widget file EchMultiSelect.php will be located within the folder 'EchMultiSelect' (take a look at the file structure). So the path to this widget-file will be protected/extensions/widgets/EchMultiselect/EchMultiSelect.php. Therefore you will need to call the widget with:
$this->widget('ext.widgets.EchMultiselect.EchMultiselect', array(...));
  • If you:
    1. Extract the zip file to some place, which results in the folder EchMultiSelect.
    2. Copy the files that are within this new folder EchMultiSelect into the protected/extensions/widgets/ directory of your application, you can use the widget as intended with:
$this->widget('ext.widgets.EchMultiselect', array(...));

Resources

Total 17 comments

#13223 report it
senad87 at 2013/05/16 04:05am
Invalid alias

I was getting

Alias "ext.EchMultiSelect.EchMultiselect" is invalid. Make sure it points to an existing PHP file and the file is readable.

Just find out that there is a wrong alias in the examples.

It's

ext.EchMultiSelect.EchMultiselect

and should be

ext.EchMultiSelect.EchMultiSelect
------------------------------------------^ with capital S on last Select word

#12023 report it
jeremy at 2013/02/20 10:16pm
fixes to work with jQueryUI 1.9.2 (in Yii 1.1.13)

If you're having problems in Yii 1.1.13 (which includes jQueryUI 1.9.2), try this:
* upgrade assets/jquery.multiselect.js to multiselect v1.13
(from the author's site: http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/)
* in assets/jquery.multiselect.js, make the following changes:
- in destroy(), comment-out
//$.Widget.prototype.destroy.call( this );
- in _setOption(), comment-out
//$.Widget.prototype._setOption.apply( this, arguments );

#11750 report it
arielon at 2013/02/01 06:20am
Some js errors found

If js errors, download the updated version of jquery.multiselect.js (http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/)

#11737 report it
c@cba at 2013/01/30 02:46pm
Reply

@Sukhwinder: I really don't know what the problem could be and don't have the required system (debian+chrome) to test. It seems to be a compatiblity problem; maybe the jQuery plugin requires things that are not included in your system..?

@Chris Backhouse: Thanks for sharing the issue and its underlying reasons.

#11243 report it
Chris Backhouse at 2012/12/31 09:12am
Form submit inconsistencies

Hi, I'm just trying out your extension and have found that with the following scenario the wrong values are posted.

Form load, specify one entry of the list as pre-selected (eg: 'value'=>array(0) )

Post -> array OK

Click the previously selected entry (unselect)

POST -> same as first post, ie: previously selected entry is still selected. You would expect an empty array.

It looks as though this could be a problem with the jQuery plugin rather than your extension....any ideas?

UPDATE: When no options are selected it returns an empty string which is not returned by the jQuery(form).serialize() function. Therefore this is not passed onto any form submit. Subsequently it appears as though $.fn.yiiGridView.update must cache previous values and, as the multi-select variable is not defined, it is not getting re-initialised and the previous value is being POSTED to the controller action.

#11165 report it
Sukhwinder at 2012/12/21 02:16am
Drop down not closing

Hi i followed your instruction to use this extension, but facing following issues: 1. Old drop down list still showing on page 2. When i open Multi Select List, it opens, i can check/Uncheck, but it is not closing , i have to reload the page. 3. It is opening in black and white colors, no hover effect

PS Im using chrome, and my OS is Ubuntu 12.04

Thanks

#11095 report it
c@cba at 2012/12/16 03:25pm
@jeremy - Thank You!!

Thank you so much for your contribution!! I wanted to do this myself for some time now, but didn't have the opportunity. I implemented your suggestion just now, it works perfectly.

Thanks again, this is very much appreciated! Do you mind if I incorporate this into the extension, with your comments?

#11094 report it
jeremy at 2012/12/16 09:15am
using EchMultiselect with CGridView

Here are the steps taken to make this very useful widget work as a 'filter' for CGridView.

The default behavior of CGridView is to do sorting/pagination/filtering in Ajax mode. After each ajax response, portions of the HTML response are used to update the grid. In this case the multi-select widget goes away and the default drop-down is displayed gain. To fix this, the caller should pass an additional option to indicate that it will be using ajax refresh, as follows:

init()
  $options_default = array(
  ..
  'ajaxRefresh' => false, // add option to redisplay multiselect widgets after ajax refresh

at the end of run(), add the following logic:

run()
  ...
  // for CGridView, <select> is refreshed on each ajax request, so the multiselect must be reapplied
  //   trigger this function to fire after ajax action is complete
  if ($this->options['ajaxRefresh']==true)
    $jscode .= "jQuery('body').ajaxComplete(function() {jQuery('#".$id."').multiselect(".$joptions."); });";
 
  Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $id, $jscode);

Usage from within CGridView:

$this->widget('CGridView',....
  'columns' => array (
    'firstColumn',
    'secondColumn',
    // use EchMultiselect for the next column
    array (
      'name'=>'thirdColumn',
      'value'=> ...., 
      'filter'=> $this->widget('EchMultiselect',
        array(
          'model' => $model,
          'dropDownAttribute' => 'thirdColumn',
          'data' => ....
          'options' => array('buttonWidth' => 80, 'ajaxRefresh' => true),
        ),
      true // capture output; needed so the widget displays inside the grid
    ),
  ),

notice the new 'buttonWidth' option. This is because my Grid layout is extremely tight. I need the multi-select buttons to be as narrow as possible, but the drop-down menus to be wider (to show the full description). The default behavior does not support this.

implementation of 'buttonWidth' option in /assets/jquery.multiselect.js:

options: {
 ...
 buttonWidth: '', /*+ JJD */
 ...
}
 
 
  _setButtonWidth: function(){
    var width = this.element.outerWidth(),
      o = this.options;
 
    if( /\d/.test(o.minWidth) && width < o.minWidth){
      width = o.minWidth;
    }
 
    // set widths
    /* JJD if buttonWidth set use it */
    if (o.buttonWidth)
      width = o.buttonWidth;
 
    this.button.width( width );
  },
 
 
  // set menu width
  _setMenuWidth: function(){
    var m = this.menu,
        o = this.options, /* +JJD */
    width = this.button.outerWidth()-
      parseInt(m.css('padding-left'),10)-
      parseInt(m.css('padding-right'),10)-
      parseInt(m.css('border-right-width'),10)-
      parseInt(m.css('border-left-width'),10);
 
     /* JJD if buttonWidth is manually set and minWidth is set and wider, use it */
     if (o.buttonWidth && o.minWidth && o.minWidth > o.buttonWidth)
       m.width(o.minWidth)
     else
       m.width( width || this.button.outerWidth() );  /* orig logic */
  },
#11092 report it
jeremy at 2012/12/15 11:41pm
easier way to hide the default drop-down

instead of hiding the default drop-down with jQuery .hide(), I suggest:

init() {
 ...
 if (!isset($this->dropDownHtmlOptions['style']))
    $this->dropDownHtmlOptions['style']='';
 $this->dropDownHtmlOptions['style'] .= ';display:none';
 ...
 
run() {
  ...
  // following line is not needed
  //echo '<script type="text/javascript">$("#'.$id.'").hide();</script>'; 
  ...
}
#10386 report it
deeptibaghel at 2012/10/24 03:12pm
In Multiselect mode, if there is a single option, it doesn't work

In Multiselect mode, if there is a single option, it doesn't work. The checkbox gets checked but it doesn't show "1 selected". Whereas it works with jquery ui demo at

http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/

Regards Deepti

#9116 report it
Vainglory07 at 2012/07/21 03:26pm
LIKE LIKE LIKE!:)))

very nice widget:))

#8531 report it
Maxxer at 2012/06/11 03:02am
@c@cba

thanks, fixed!

#8527 report it
c@cba at 2012/06/10 05:09pm
@maxxer - preselect

Hi maxxer,

please note the following two important points:

  1. The data has to be an associative array. It will be used to generate the dropdown list.
  2. The dropDownAttribute has to be an array of values; a one deminesional array that contains the preselected values to be specific.

In your example you set

$model->my_search_parameter = CHtml::listData(MyModel::model()->findAll(), 'codice','codice');

This is an associative array that can be used as the 'data' to populate the dropdown list. It can not be used as the 'dropDownAttribute'.

I don't know what MyModel::myDropDownListMethod() is doing/returning, so I cannot say if there lies a problem.

In your Controller Action, there shoud be something like this:

$model->my_options = CHtml::listData(MyModel::model()->findAll(), 'id','values');
/* 
You can load the preselected values from somewhere, from another model for example. But make sure that eventually $model->my_preselected_values is a one dimensional array, like:
*/
$model->my_preselected_values = array('id_1', 'id_2', 'id_3');

Then your view file should look like:

'model' => $model,
'dropDownAttribute' => 'my_preselected_values', 
'data' => $model->my_options,

We discussed this topic of preselected values here in the forum, you might want to take a look. There are a few good examples that shoud make it clearer...

Best regards...

#8492 report it
Maxxer at 2012/06/07 08:59am
preselect

hi. I cannot preselect entries. I'm using the widget in a _search.php form, where I use a modified advanced search. In the action displaying the form I added something like this:

$model->my_search_parameter = CHtml::listData(MyModel::model()->findAll(), 'codice','codice');

the widget is then defined this way:

$form->widget('ext.widgets.EchMultiSelect', array(
                'model' => $model,
                'dropDownAttribute' => 'my_search_parameter', 
                'data' => MyModel::myDropDownListMethod(),
                'dropDownHtmlOptions'=> array(
                    'style'=>'width:378px;',
                ),  
                'options' => array( 
                    'header'=> Yii::t('string','Seleziona gli hotspot'),
                    'minWidth'=>350,
//                    'position'=>array('my'=>'left bottom', 'at'=>'left top'),
                    'filter'=>true,
                    'noneSelectedText'=>'-- '.Yii::t('string','seleziona almeno un hotspot').' --',
                    'checkAllText' => Yii::t('string','Seleziona tutte'),
                    'uncheckAllText' => Yii::t('string','Deseleziona tutte'),
                    'selectedText' =>Yii::t('string','# selezionato/i'),
                ),  
                'filterOptions' => array( 
                    'placeholder'=>Yii::t('string','Ricerca'),
                    'label' => Yii::t('string','Filtra:'),
                ),  
 
            ));

but there's always NO item preselected.

#6929 report it
c@cba at 2012/02/14 04:43am
@bonnie

Hi bonnie,

You just have to extract the files under protected/extensions/widgets/. Those file paths show only where the files should be located after the extraction.

If you call the widget with

$this->widget('ext.widgets.EchMultiselect', ...);

then you don't need to include/import the files in your config file. Because you are specifying the exact path with ext.widgets.EchMultiSelect.

I hope it's clearer now?

#6925 report it
bonnie at 2012/02/13 11:51pm
Thanks for this extension

Hi, c@cba nice extension but can you specify exactly which file should this information included.

protected/extensions/widgets/EchMultiSelect.php
protected/extensions/widgets/assets/jquery.multiselect.js
protected/extensions/widgets/assets/jquery.multiselect.css
protected/extensions/widgets/assets/jquery.multiselect.filter.js
protected/extensions/widgets/assets/jquery.multiselect.filter.css
#6903 report it
c@cba at 2012/02/12 06:34am
Changes/Additions

What would you think about the following changes/additions to this widget:

  • Change the button element (generated by the Multiselect widget) into a textfield. Make it serve as the filter-textfield (that is: filter the options as text is added into this textfield).
  • Add the option to make the texfield un-editable if filter is set to false.
  • Replace the two text-options 'Check All' and 'Uncheck All' in the header with a checkbox, that controls all checkboxes (check->check all, uncheck->uncheck all).
  • Add the option to hide the checkboxes in multiple selection mode (in single select mode, they are hidden), and highlight the selected elements instead (like it is done in the single selection mode).
  • Add the option to enter a new text (different from the options) into the textfield (like the 'allowText' option of this combobox)
  • Currently, when menu is closed via 'tab' or 'esc', the focus is lost and I can't move to the next element in the form with 'tab'. Thus: make it so, that user can move along form fluently without using the mouse.

Does someting speak against (one of) these changes?

Leave a comment

Please to leave your comment.

Create extension