Serge Vinogradoff
Serge Vinogradoff

Reputation: 2272

remove a blank option of select field that was generated by SimpleForm

I have this piece of code:

= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"]

Choices["Categories"] is just a hash of key=>value pairs.

SimpleForm generates a select field with all needed options, but it also makes the first option blank.
This blank option is present in all select fields that were generated by SimpleForm.

But I don't want to have a blank option. Is there a way to get rid of it?

Something like :allow_blank_option => false?

I tried to make a presence validation of this attribute hoping that SimpleForm will detect it, but it didn't help.

Upvotes: 57

Views: 38348

Answers (3)

Soumitra Sarkar
Soumitra Sarkar

Reputation: 628

To remove a blank field from select it is necessary to show the selected so add selected: 1 Then set prompt to anything like prompt: "Please Select" The final output will be <%= select("social_links",:option_id, Option.all.collect {|p| [ p.name, p.id ] },{ selected: 1 , prompt: "Please Select"}, { class: 'form-control' , required:true})%>

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124419

You can pass a include_blank: false, include_hidden: false option:

= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"], include_blank: false, include_hidden: false

Upvotes: 106

Antonio Jha
Antonio Jha

Reputation: 1309

or you can customize call back action in your model to remove any empty string in the array parameter, assuming a parameter with the name "types":

before_validation :remove_empty_string

def remove_empty_string
  types.reject! { |l| l.empty? }
end

Upvotes: 2

Related Questions