Ruby on Rails 3: How to create a custom form element / form field input method?
I would like to create a custom form element for Ruby on Rails 3 and package it as a gem. I am coming from a PHP (Zend Framework) background, where it is easy to create custom form elements to use within your application. Being new to Ruby on Rails, I don't know how to start, where to put my code, and which classes to extend. Can you please point me in the right direction? This is the code that I want to end up with:
<%= form_for(@model) do |f| %>
<div class="field">
<%= f.label :field_name %><br />
<%= f.my_custom_element :field_name %>
</div>
<% end %>
...which will generate some HTML like this:
<div class="field">
<label for="model_field_name">Notes</label><br>
<input type="text" name="model[field_name][field1]">
<input type="text" name="model[field_name][field2]">
<input type="text" name="model[field_name][field3]">
</div>
..then when the user submits the form, there will be some custom validation, and custom logic to stitch the fields together again into one field before Rails saves the data to the database.
How can I create this custom form element to do this? (By the way, I've been calling it a "custom form element" because that's what it's called in Zend Framework开发者_StackOverflow. If Rails has a different name for this, please correct me so I can have an easier time finding information on this subject.)
If you want validations and MVC I suggest start looking into Rails Engines.
http://edgeapi.rubyonrails.org/classes/Rails/Engine.html
Andrew, you can start with your own helper that will be gerenate HTML code as result. when you feel comfortable with it, move forward to see how default helpers look like
# File actionpack/lib/action_view/helpers/form_tag_helper.rb, line 292
292: def check_box_tag(name, value = "1", checked = false, options = {})
293: html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
294: html_options["checked"] = "checked" if checked
295: tag :input, html_options
296: end
after that dive into the source :)
精彩评论