Joe
Joe

Reputation: 1765

Capitalize f.text_field

I have a form_for and I want that any value inside x.textField appear with the first letter in Upcase (I'm talking about the edit where the textfield are prefilled by the db values).

Upvotes: 8

Views: 6105

Answers (4)

Chris Chattin
Chris Chattin

Reputation: 482

You can do this with CSS...

= f.text_field :some_attribute, style: 'text-transform: capitalize;'

Upvotes: 7

Muhammad Suleman
Muhammad Suleman

Reputation: 2922

you can also do this in controller's create/update action like as given below

def create

  @user = User.new(params[:user])
  @user.name = params[:user][:name].capitalize

  if @user.save
   #do something
  else
   #do something else
  end

end

Upvotes: 0

jemminger
jemminger

Reputation: 5173

Pan Thomakos's solution will work, but if you don't want to have to add :value => f.object.name.capitalize to every text field on the form, you could look into writing your own FormBuilder.

Put this somewhere in your load path, like lib/capitalizing_form_builder.rb

class CapitalizingFormBuilder < ActionView::Helpers::FormBuilder

  def text_field(method, options = {})
    @object || @template_object.instance_variable_get("@#{@object_name}")

    options['value'] = @object.send(method).to_s.capitalize

    @template.send(
      "text_field",
      @object_name,
      method,
      objectify_options(options))
    super
  end

end

Usage:

<% form_for(@post, :builder => CapitalizingFormBuilder) do |f| %>

  <p>
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.text_field :description %>
  </p>
  <p>
    <%= f.submit 'Update' %>
  </p>

<% end %>

Upvotes: 2

Pan Thomakos
Pan Thomakos

Reputation: 34350

You can capitalize it like this:

<%= form_for ... do |f| %>
  <%= f.text_field :name, :value => f.object.name.capitalize %>

Upvotes: 6

Related Questions