simple_form - how do I create radio buttons with nested input text boxes - ruby-on-rails-3

I'm using simple_form to render my forms and trying to get the following behavior: I want the client to choose from 3 options. In every option he supplies additional field or two.
So I'd like something like this:
Please set your preferences:
o Pay me on a specific day - [input field to get the day]
o Pay me a specific amount of money - [input field for the amount]
o Pay me on a regular basis - [radio buttons to choose between weekly/monthly basis]
I can create the radio buttons as follows, but can't add nested fields under them:
<%= simple_form_for #client, action: 'edit_payment_method' do |f| %>
<%= f.input :payment_type, label: 'Please set your preferences:',
collection: [ ['Pay me on a specific day', :specific_day],
['Pay me a specific amount of money', :specific_money],
['Pay me on a regular basis', :regular_basis]
], as: :radio_buttons %>
<%= f.button :submit, 'Submit' %>
<% end %>
What would be the best way to create the nested text boxes?
As for the fields, I don't need to send them to different controllers (per payment_type), it's fine if I send them all to one method and read the relevant values according to the payment type he chose.
Thanks! Zach

The simple_form collection_radio_buttons is likely what you want. Its options parameter accepts a block which allows you to customize what is rendered with each radio button. Take a look at the example in rdocs here.
Edited:
Here is basically what you need to do in a relatively generic way (hasn't been tested, but I'm running something similar). Put your additional controls in the partial for each radio button:
<% radio_buttons = [
{ :text => 'Pay me on a specific day', :value => :specific_day, :partial => "<textbox_partial_name>", :locals => { :any_locals => :your_partial_needs} },
{ :text => 'Pay me a specific amount of money', :value => :specific_money, :partial => "<textbox_partial_name>", :locals => { :any_locals => :your_partial_needs} },
{ :text => 'Pay me on a regular basis', :value => :regular_basis, :partial => "<radio_partial_name>", :locals => { :any_locals => :your_partial_needs} },
] %>
<%= simple_form_for #client, action: 'edit_payment_method' do |f| %>
<%= f.label t("account.update_payment_method.title") %>
<%= f.collection_radio_buttons :payment_type, (collection.collect do |r| [r[:text], r[:value], r[:partial].nil? ? "" : r[:partial], r[:locals].nil? ? {} : r[:locals]] end), :second, :first do |builder| %>
<%= builder.label{builder.radio_button(:class => 'payment_method_options') + builder.text} %>
<% unless builder.object[2].blank? %>
<%= render :partial => builder.object[2], :locals => builder.object[3] %>
<% end %>
<% end %>
<%= f.button :submit, 'Submit' %>
<% end %>
You can omit :partial for any radio button that doesn't need additional controls, along with :locals if your partial doesn't need it. There are also ways to simplify this code for your situation, but this example illustrates how to add more complex control structures to each radio button if needed.

OK.. I've managed to solve this somehow, not sure that it's the best alternative, but I'm posting it so if someone needs it in the future he at least has something to start with.
I went with creating a "regular" form using simpleform and then using JQuery to move the inner input fields (which were created regularly) next to the radio buttons.
Add JQuery support to your rails app:
add gem "jquery-rails" to your Gemfile
bundle install
rails generate jquery:install
The form I've used (regular simpleform):
Notice the class that is attached to the radio buttons and the ids that are attached to the input fields. I'll use it later to move the elements.
<%= simple_form_for #client, url: 'update_payment_data' do |f| %>
<%= f.input :payment_type, label: t('account.update_payment_method.title'),
input_html: { class: 'payment_method_options' },
collection: [ [t('account.update_payment_method.sum_based.title'), :amount],
[t('account.update_payment_method.days_in_month_based.title'), :days_in_month],
[t('account.update_payment_method.optout.title'), :optput]
], as: :radio_buttons %>
<%= f.input :payment_amount, label: "Payment amount threshold",
input_html: { id: 'payment_amount_box' } %>
<%= f.input :payment_days_in_month, label: "Payment days in month",
input_html: { id: 'payment_days_in_month_box' } %>
<%= f.button :submit, t('account.update_payment_method.update') %>
<% end %>
In the same page - the JQuery code:
<script>
$(document).ready(function() {
var amount_box = $("#payment_amount_box");
var amount_box_parent = amount_box.parent();
amount_box.detach().appendTo($(".payment_method_options:eq(0)").parent());
amount_box_parent.remove();
var dim_box = $("#payment_days_in_month_box");
var dim_box_parent = dim_box.parent();
dim_box.detach().appendTo($(".payment_method_options:eq(2)").parent());
dim_box_parent.remove();
});
</script>
I think it's pretty self-explanatory, it just looks for what is going to be the inner input fields (by id) and moves them into the appropriate place under the span that simpleform creates for each radio button.
I had to play a little bit with the css to make it look how I wanted (display:block for example), but that's more or less it.
Hope it helps.. Zach

Related

undefined method `model_name' in a partial rendered by different controller

I'm trying to render this form:
<form class="form-inline">
<%= simple_form_for #prospect,
:url => url_for(:action => 'create', :controller => 'prospects'),
:method => 'post' do |f| %>
<%= f.error_notification %>
<%= f.input :name, placeholder: 'Name', label: false %>
<%= f.input :email, placeholder: 'Email', label: false %>
<%= f.input :interests, placeholder: 'Tell us what you were searching for', label: false, value: params[:search] %>
<%= f.error :base %>
<%= f.button :submit, "Submit", :class=> "btn" %>
<% end %>
Using this partial:
<%= render partial: 'prospects/novideo_capture' %>
The partial is in a view controlled by Videos#index controller, and I keep getting this error: 'undefined method `model_name' for NilClass:Class'
This is my prospects controller:
class ProspectsController < ApplicationController
def index
#prospects = Prospect.all
end
def new
#prospect = Prospect.new
end
def create
#prospect = Prospect.new(params[:prospect])
if #prospect.save
render "thanks_for_interest"
else
render "novideo_capture"
end
end
I'm not sure what I'm going wrong, although I'm pretty sure it's a simple solution. I've seen a lot of similar questions around SO and tried all their answers, but none of them seem to work for this situation.
Thanks for any help...
EDIT: Adding
#prospect = Prospect.new
to the videos index controller stops the error occurring, but I don't feel it's the right way to do this. It also doesn't actually make the form use the prospects controller.
EDIT2: I now have the partial rendering correctly (I think), and my videos#index calls the partial like this:
<%= render partial: 'prospects/novideo_capture', :prospect => #prospect %>
Then simple_form in the partial looks like this:
<form class="form-inline">
<%= simple_form_for :prospect,
:url => url_for(:action => 'create', :controller => 'prospects'),
:method => 'post' do |f| %>
...
<% end %>
However it's not actually submitting the form with the prospects controller. Any ideas why?
Check your markup. You're wrapping a simple_form inside another form. Since the first form tag has no action associated with it (<form class="form-inline">), that form will submit against the current URL, which is the video#index.
You're going to want something like this:
<%= simple_form_for :prospect, :url => etc, :method => 'post', :class => "form-inline" do |f|
...
<% end %>
Losing the leading (redundant) form-inline form tag and you'll be fine.

How to create formtastic form with multiple language support (Internationalization)

I need to set up two languages for a single form using internationalization.
This is the proposed form page
<%= semantic_form_for #detail do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<%= f.input :dob %>
<%= f.input :gender, :as => :radio, :label => "Gender", :collection => [["Male", 'male'], ["Female", 'female']] %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>
This is wk.yml file
wk:
formtastic:
labels:
detail:
dob: "Data of birtha"
name: "Youre Nama"
gender: "Gendera""
This is en.yml file
en:
formtastic:
labels:
detail:
dob: "Date of Birth"
name: "Your Name"
gender: "gender"
I have added Formtastic::SemanticFormBuilder.i18n_lookups_by_default = true in formtastic.rb initializer.
I was successful in using en.yml.
I need to switch from 'en' to 'wk' and vise-verse.
How to achieve it via drop down box?
That's not something related to formstatic, but rather to your rails code.
All you have to do in order to switch to wk is
http://guides.rubyonrails.org/i18n.html
I18n.locale = :wk
In order to let your client to choose his language for the website, probably a good place to start is on this link: http://guides.rubyonrails.org/i18n.html
If all you want is to update the form (and not the rest of the website) in different languages on a user action, like selecting the language from a select box, you can use an ajax listener on the select box, that could require something like "http://www.yourwebsite.com/:locale/form/new" which will answer with an ajax action and will replace your form with the selected language (so on :locale you will pass the value of your select box for the language).

rails 3 link_to with nested content_tag to create <a href with nested span - how to?

Hi I got a noob question, I want to create the following HTML result:
TEXT<span class="arrow-big"></span>
In the above HTML I want to have text with a span-class to style in an image via css.
When I try the following implementations the result reflects just one part of the needed implementation:
<%= link_to "TEXT", controller_path, :class => "button-big layer" %>
results in:
TEXT
and
<%= link_to(content_tag(:span, "", :class => "arrow-big"), controller_path, :class => "button-big layer") %>
results in:
<span class="arrow-big"></span>
Does anyone know how to accomplish?
You could also nest tags by using alternative syntax for link_to helper
<%= link_to controller_path, :class=> "button-big layer" do %>
Text
<%= content_tag(:span, "", :class => "arrow_big" %>
<% end %>
Simply concatenate your text with the 'span':
<%= link_to(("TEXT" + content_tag(:span, "", :class => "arrow-big")).html_safe,
controller_path,
:class => "button-big layer") %>
You'll need the .html_safe around the concatenation since the + operator will otherwise escape the HTML of the content_tag.
Reading your question I did solve my problem.
Than I propose another way to answer your question.
You could create a helper method to make this kind of link that you need.
It would be something like this
def link_with_text_and_span(href, text, span_options= {}, link_options = {})
span_tag = content_tag(:span, span_options[:content] || '', :class => span_options[:class] || '')
link_to(span_tag, href, :class => link_options[:class] || '')
end
The good about it is that your view will be cleaner.
Then you can just call this helper method in your view
<%= link_with_text_and_span("/controller/action", "TEXT", {class: 'arrow-big'}, class: button-big) %>
PS: This code can be improved for sure, if other users want to, please do it.
Here's another way you could use without the content_tag. Not the cleanest but it works!
<%= link_to '<span class="arrow_big"></span>'.html_safe, controller_path, class: "button-big layer" %>

How to access one model within another model in Rails..?

I have one data model 'object' with fields->object_id, object_name.
That is: http://localhost:3000/objects/
I have created another model 'front_pages' (not created any migration in this, instead I have created some pages like 'search.html.erb'(by hand) and the associated controllers).
That is: http://localhost:3000/front_pages/
My question is: How to access/search the items stored in the 'object' database within the 'search.html.erb'.
"These two are in the same rails project folder"
-> How to display the search results into an HTML.erb file?
views/static_pages/show.html.erb
<% #npsobject.each do |npsobjects| %>
Nps:
Nps type:
Nps name:
|
Static_page Controller
class StaticPagesController < ApplicationController
def show
#npsobject=Npsobject.find(:all, :conditions => ['nps_name LIKE ?', "%#{params[ :search]}%"]);
end
views/static_pages/new.html.erb
<%= form_tag( { :action =>"show"}, { :method => "get"}) do %> # The action path is ok??
<%= text_field_tag :search, params[:search], :class => 'inputBox' %>
"button") %>
Please verify the above codes and guide me through, as Im new to RoR..:)
You need to move your
#npsobject = Npsobject.find
into show action
and then each it into your views/static_pages/show.html.erb
<% #npsobject.each do |nps| %>
<%= nps.nps_name %>
<% end %>

Why is my nested text_area helper adding html tags?

I have a text_area in a partial in a complex form that is called like so
<%= f.fields_for :notes do |notes_form| %>
<%= render :partial => 'note', :locals => {:f => notes_form, :operation => f, :count => operation.notes.count} %>
<% end %>
<p><%= add_child_link "Add note", :operation_notes %></p>
and the partial looks like this
<% count ||= 2 %>
<div class='fields'>
<%= f.text_area :note_text, :rows => "4", :class => "notes" %>
<%= remove_child_link "x", f, count %>
</div>
There can be many notes on the form hence the add and remove child links.
The issue I'm having is that if I add a note with the text 'abcd', when I bring up the edit form I get '<p>abcd</p>'. If there are line breaks in the note it adds <br /> tags. The text_area form helper seems to be using the simple_format helper but I have no idea why. Can anyone help as this is very undesirable behaviour?
Ah solved,
Earlier on the same page I was displaying the note and using simple_format to format it with
<%= simple_format note.note_text %>
It seems that simple_format is somewhat destructive as after this, a call to note.note_text always returns the formatted text. If I change the above to
<%= simple_format note.note_text.dup %>
then the note_text attribute is not altered and I get the appropriate results.
I will have to look more closely at simple_format but this really strikes me as undesirable behaviour.
EDIT
It looks like this has been corrected in Rails 3.1
I would suspect that you have something in your Note model that is processing the text. Check for callbacks in this model.