Back to the front page

Highlighting Select2 Fields with Rails Validation

Select2 is a great way to add customizable select boxes with support for searching, tagging, remote data sets, infinite scrolling, and much more to your Rails application.

While setting up select2 is beyond the scope of this post, one useful Rails ability that you lose when using select2 fields inside of a Rails form helper is the automatic highlighting of fields that fail your rails model validations.

Highlighting Errors

image

In the above image you can see that rails was properly able to highlight the name text field and label but it was not able to highlight the entity field.

Rails handles the highlighting of invalid fields by wrapping them in a field_with_errors class.

<div class="field_with_errors">  
    <label for="client_account_name">Name</label>
</div>

<div class="field_with_errors">  
    <input class="one_third" id="client_account_name" name="client_account[name]" type="text" value="" />
</div>  

The Problem

The reason Rails does not auto highlight select2 fields is because select2 uses hidden fields and javascript to repalce the standard select field and therefore rails is not able to automtically wrap the select2 field in the field_with_errors class.

<div class="field">  
    <div class="field_with_errors">
        <label for="client_account_entity">Entity</label>
    </div>

    <input class="js_client_account_entity_select one_third" id="client_account_entity_id" name="client_account[entity_id]" type="hidden" />

</div>  

You can see above that the label field is wrapped in the correct error class but the select field is not.

The solution

In order to get the Select2 field properly wrapped in the field_with_errors class you have to manually add the logic into your view code.

In our haml for this page this entitailed:

.field
     = f.label :entity
    %div{:class => (account.errors.messages[:entity].present? ? "field_with_errors" : nil) }
        = f.hidden_field(:entity_id, class: "js_client_account_entity_select one_third")

Then in the css sass file for this page add:

.field_with_errors
  .select2-container
    a
      background: #fbe8e5

Now when the select2 field fails rails validation, it will highlight properly with the rest of the failing fields.

image

Comments

comments powered by Disqus