Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 automatically adding blank value

I'm using select2 for a multiple selector. Currently this is in my HTML file:

 <%= form.select "page_request_set_ids", @multiautocomplete_set_options.unshift(""),
 {}, id: "page-request-sets", multiple: true,
 allowClear: true, data: {placeholder: "Start typing sets..."} %>

@multiautocomplete_set_options is an array of strings. When I go to access :page_request_set_ids later, the strings I typed in are there, along with an empty string.

I've tried to remove the unshift(""), which kept my placeholder, but did not remove the issue of the blank string in :page_request_set_ids.

Any ideas?

like image 993
nhyne Avatar asked Sep 27 '22 00:09

nhyne


1 Answers

Directly taken from the select documentation:

Gotcha

The HTML specification says when multiple parameter passed to select and all options got deselected web browsers do not send any value to server. Unfortunately this introduces a gotcha: if an User model has many roles and have role_ids accessor, and in the form that edits roles of the user the user deselects all roles from role_ids multiple select box, no role_ids parameter is sent. So, any mass-assignment idiom like

@user.update(params[:user])

wouldn't update roles.

To prevent this the helper generates an auxiliary hidden field before every multiple select. The hidden field has the same name as multiple select and blank value.

Note: The client either sends only the hidden field (representing the deselected multiple select box), or both fields. This means that the resulting array always contains a blank string.

In case if you don't want the helper to generate this hidden field you can specify include_hidden: false option.

So bottom line is to add:

include_hidden: false

like image 147
Paulo Fidalgo Avatar answered Oct 22 '22 16:10

Paulo Fidalgo