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


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 class="field_with_errors">  
    <input class="one_third" id="client_account_name" name="client_account[name]" type="text" value="" />

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>

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


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:

     = 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:

      background: #fbe8e5

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



comments powered by Disqus