views:

85

answers:

1

Using Rails, I would like to add: <span class='req'>&bull;</span> within my <label> tags in my views, if I set an option on the label form helper; i.e.

<%= f.label :address_1, "Address 2:", :req => true -%>

should produce:

<label for="model_address_1"><span class='req'>&bull;</span> Address 1:</label>

rather than:

<label for="model_address_1" req="true">Address 1:</label>

as it does now. I realise I may have to override the default form builder or create my own form builder, but don't know how to do this. Any suggestions? Thanks in advance!

Update: I'm doing this in an attempt to DRY up my code, and I realise that I could just paste the span snippet above into all the labels in all of my views but I'd like to avoid that.

+1  A: 

This is untested, but something along these lines should work.

# in lib/labeled_form_builder.rb
class LabeledFormBuilder < ActionView::Helpers::FormBuilder
  def label(field_name, label = nil, options = {})
    if options.delete(:req)
      label ||= field_name.to_s.humanize
      label = @template.content_tag(:span, "&bull;", :class => "req") + " " + label
    end
    super(field_name, label, options)
  end
end

And then use that builder in your view

<%= form_for @item, :builder => LabeledFormBuilder do |f| %>

You might be interested in Episode 3 of my Mastering Rails Forms screencast series where I go into detail on creating form builders.

ryanb
Works a treat Ryan, thanks very much! I'll check the screencast out :-)
Gav