开发者

Adding a custom input field in formtastic?

开发者 https://www.devze.com 2023-03-23 17:32 出处:网络
I can\'t figure out, or find any solutions to a very simple question: \"How can I define my own input field in formtastic?\"

I can't figure out, or find any solutions to a very simple question: "How can I define my own input field in formtastic?"

This is what I got:

<%= semantic_form_for @someFantasticVariable, :url => "/someFantasticUrl.html" do |f|%>  
    <%= f.inputs do %>
        <%= f.input :something_else_id, :required => true , :as => :select, :collection   => SomethingElse.find(:all), :label =>"The something else"%>
        <%= f.input :fantastic_max_cost, :label => "Budget (max cost)"%>  
    <%end%>


    <%= f.buttons do%>
        <%= f.commit_button :button_html => { :class => "primary", :disable_with =>     'Processing...', :id => "commitButton"}%>
    <%end%>
<%end%>

Now..

I want to have a very simple thing. I want to ad a field that is not part of the model. I want to have a date field that I can use to calculate some stuff in my controller. So I want to do this:

<%= f.inputs do %>
    <%= f.input :something_else_id, :required =&g开发者_开发百科t; true , :as => :select, :collection   => SomethingElse.find(:all), :label =>"The something else"%>
    <%= f.input :fantastic_max_cost, :label => "Budget (max cost)"%>  
    <%= f.input :start_date, :as => :date , :label => "Start date"%>
<%end%>

But apparetly I'm not allowed, and I can't find any way to do this through my thrusted googling. Any help / ideas?


If you have some attribute that is not part of your model, then a getter and a setter should exist on the model:

def start_date
end

def start_date=(arg)
end

Then you can calculate your staff on a controller or whatever you want:

...
puts params[:somefantasticvariable][:start_date]
...

But this is a quick formtastic hack, you should find some better way, like non-formtastic input with some css etc.


Ruby provides a database-less construct called an attr_accessor. It is the equivalent of writing setter and getter methods. Formtastic will see this attribute similar to a database-backed attribute.

In your @someFantasticVariable model:

attr_accessor :start_date

If using attr_accessible in your @someFantasticVariable model, be sure to add the start_date variable there too:

attr_accessible :start_date

Because the attribute is type-less, Formtastic cannot derive the HTML input field to use. You will need to manually set the input type using :as. For your example:

<%= f.input :start_date, :as => :date_select %>

Cite:

  • http://apidock.com/ruby/Module/attr_accessor
  • https://github.com/justinfrench/formtastic#the-available-inputs
0

精彩评论

暂无评论...
验证码 换一张
取 消