Add class to custom form_for label

DawgOnKing picture DawgOnKing · May 27, 2014 · Viewed 7.6k times · Source

How do I add a custom class to a form_for else statement?

<%= form_for(@user) do |f| %>

      .
      .
      .
      <%= f.label :name, 
        if @user.errors[:name].blank?
          'Name'
        else
          'Name ' + @user.errors[:name].to_sentence
        end
      %>

I've tried:

else
  'Name ' + @user.errors[:name].to_sentence, class: "some_class"
end

Also tried:

else
   'Name ' + @user.errors[:name].to_sentence, :class => "some_class"
end

but both generate unexpected errors.

I'm simply customizing the input label to display the validation error upon form submission and would like to change the text color.

Answer

zishe picture zishe · May 27, 2014

I guess you can do it in one line:

<%= f.label :name, (@user.errors[:name].blank? 'Name' : 'Name ' + @user.errors[:name].to_sentence) %>

Then:

<% if @user.errors[:name].blank? %>
  <%= f.label :name, 'Name' %>
<% else %>
  <%= f.label :name, 'Name ' + @user.errors[:name].to_sentence, :class => "some_class"  %>
<% end %>