Adding * to required form labels
Asked Answered
S

3

8

Does anybody have a nice way of adding * to required form labels, without having to turn to tools like SimpleForm?

I did not like the way SimpleForm added all these weird wrappers and classes to my stuff. I thought the point of SimpleForm was to allow you to write simple, semantic form ERB (which it most certainly does) - but not at the same time mess up your existing layout by adding wrappers and classes at random. I always style my forms before I bring them to Rails, so I like to tell it what classes to use, not the other way around.

Sedative answered 8/3, 2012 at 17:22 Comment(5)
Please don't add signatures or taglines to your posts.Billiot
Looks like you don't need simple form.Beffrey
"I like to tell it what classes to use, not the other way around." You're doing it wrong. Style your forms after you bring them to Rails. Rails is opinionated software. If you want to benefit from using the software, rather than fighting with it, do it the Rails way. Also, almost your entire question is an off-topic rant about how much you dislike SimpleForm. Not acceptable here. Please keep your questions unbiased an on-topic.Billiot
Nope, one thing at the time, please sir. Style your project before you bring it into Rails. That way you don't have to focus on design and development at the same time. You will go mental. As for the unnecessary semantics of SimpleForm's output HTML, I would like y'all to take a moment to reflect upon the saying: "Perfection is achieved, not when there's nothing left to add, but when there's nothing left to take away."Sedative
BTW, with SimpleForm 2 you can configure these wrappers in your own way. There are a big section in README about this - github.com/plataformatec/simple_formWortman
T
32

Can't you just simply style your labels?

Your label:

<label class="required">MyRequiredField</label>

Your css.

label.required:after{content:"*"}

Or am I missing what you're trying to accomplish?

Tamasha answered 8/3, 2012 at 17:52 Comment(1)
Spot on miked! Thank you very much indeed!Sedative
R
0

If you don't like their solution you can see how they implemented and roll your own:

https://github.com/plataformatec/simple_form/blob/master/lib/simple_form/helpers/required.rb

Rube answered 8/3, 2012 at 17:57 Comment(0)
D
0

Hello after twelve years. Here is my solution. It will probably miss some non-standard cases, but is good enough for now. BTW, I'm not using Simple Form.

def label_class(model, field, other_classes)
  # usage example: label_class(MyModel, :title, 'mylabel')
  # will return "mylabel required" if the field is required
  # add to css: label.required:after {content:"*"}
  crit = model.validators.select { |i| i.kind == :presence}.find { |i| i.attributes.include?(field) }
  other_classes + (crit ? ' required' : '')
end
Danyel answered 19/9, 2024 at 16:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.