small medium large xlarge

15 May 2008, 16:13
Cindy (2 posts)

I love Mike’s recipe for DRY forms. Has anyone added a way to show the user that a field is required? Usually I would add an asterisk or something next to the field name/label. I had thought about simply adding :class, but that adds it to the input box, whereas, I’d want to add it to the label. Any ideas?

24 Jun 2008, 14:44
David Blankenship (6 posts)

Would you be able to change the label’s :after with CSS to include an asterisk? Or, you could modify the form builder fields to allow an option for :required => true and show the asterisk based on the value. Quick and dirty might be to pass it through to the field/field_with_errors partial and then evaluate it in there.

24 Jun 2008, 20:16
David Blankenship (6 posts)

It’s very rough and could be improved on easily, but something like:

def build_shell(field, options)
    @template.capture do
      options[:required] ||= false
      label_options = (options.has_key?(:label)) ? options[:label] : field.to_s.humanize()
      label_options += '<span class="req">*</span>' unless (options.has_key?(:required) and options[:required] == false)
      options.delete :required
      locals = {
        :element => yield,
        :label => label(field, label_options)

That should allow you to use :required => true and have it display a span inside the label.

You must be logged in to comment