Capitalize f.text_field

时光毁灭记忆、已成空白 提交于 2019-12-07 01:40:44

问题


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).


回答1:


You can capitalize it like this:

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



回答2:


You can do this with CSS...

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




回答3:


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 %>



回答4:


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


来源:https://stackoverflow.com/questions/4951202/capitalize-f-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!