Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TbSelect2 - multiselect and placeholder lead to empty selection #717

Closed
bluezed opened this issue Nov 21, 2013 · 3 comments
Closed

TbSelect2 - multiselect and placeholder lead to empty selection #717

bluezed opened this issue Nov 21, 2013 · 3 comments

Comments

@bluezed
Copy link

bluezed commented Nov 21, 2013

I've got this TbSelect2 on a page:

$this->widget(  'bootstrap.widgets.TbSelect2',
                array(  'model' => $model,
                        'attribute' => 'reporter_id',
                        'data' => CHtml::listData(LdapUser::getAllActive(), 'id', 'name'),
                        'htmlOptions' => array('multiple'=>true),
                        'options' => array('placeholder'=>Yii::t('portal', 'reporter'))
                )
            );

When nothing is selected it always looks like this:
http://s19.postimg.org/bnx6z3xer/Tb_Select2.png

There's an empty selection box.

When I either set 'multiple'=>false or remove the 'placeholder' then it looks ok.

I guess it has to do with this in the TbSelect2 class?

$this->addEmptyItemIfPlaceholderDefined();

Any way to get around this!?

@ddenev
Copy link

ddenev commented Nov 24, 2013

Yes, the problem is that $this->addEmptyItemIfPlaceholderDefined() is called even for multiple selects. The select2 docs say that an empty option should be added only for non-multi-value selects:

"Note that because browsers assume the first option element is selected in non-multi-value select boxes an empty first option element must be provided () for the placeholder to work."

So in order to fix this problem, this:

$this->addEmptyItemIfPlaceholderDefined();

should be replaced with this:

if (empty($this->htmlOptions['multiple'])) {
    $this->addEmptyItemIfPlaceholderDefined();
}

Additionally, the proper way to add an empty option as the first element is (in prependDataWithEmptyItem()):

$this->data = array_reverse($this->data, true);
$this->data[''] = '';
$this->data = array_reverse($this->data, true);

Otherwise the empty option is added to the end and the single-select will still show "undefined".

@bluezed
Copy link
Author

bluezed commented Nov 25, 2013

Thanks for the help!

I've made the changes in my project and it appears to work correctly now.

Just made a Pull Request too: #719

@digitalcrab
Copy link
Contributor

Hello guys! @drank @bluezed
Thank you for your issue, now it is fixed in master branch and will be included into the next release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants