I have followed Ryans railscast #196 (revised) in order to dynamically add and remove fields to a nested form. It seems to be working just fine but I am having two issues.
I have 2 fields in the nested form (child area) that use the JQuery datepicker and as such have a class on them in the partial that displays the initial records. Initially the form is created with just 1 child. On this 1st child row the datepicker works just fine. However, when a new row is added the 2 fields with the datepicker no longer work. I believe the issue is due to the fact that when the new record gets created it does not assign the class to them, therefore the JS will not work :( No idea how to go about attempting to fix this, if it's even possible. If this is not possible then do I need to have a button to add a new record that will basically do this and refresh the form? I am hoping there's a way to do this dynamically since it just looks smoother.
When I go to edit the above record the same 2 fields are not showing the actual dates. The dates are fine and I can see that they are saved in the DB. I have another form that has a date field with the datepicker but that field is at the header and it is showing a value when editing the field. Obviously, the code I have to set the value of the date field is just not working. Again, would appreciate some help. The code is below for the partial view of these two fields.
<% fromdate_display = :fromdate %>
<%= f.text_field fromdate_display, placeholder: "mm/dd/yyyy", required: true, id: "price_fromdate", value: :fromdate.try(:strftime, "%m/%d/%Y") %>
<%= f.hidden_field :fromdate, id: "price_fromdatealt" %>
<% todate_display = :todate %>
<%= f.text_field todate_display, placeholder: "mm/dd/yyyy", required: true, id: "price_todate", value: :todate.try(:strftime, "%m/%d/%Y") %>
<%= f.hidden_field :todate, id: "price_todatealt" %>
I have tried changing the value: to be something as follows, but that throws an error:
value: #plan.plan_prices.fromdate.try(:strftime, "%m/%d/%Y")
Error message thrown:
undefined method `fromdate' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PlanPrice:0x36eb428>
I think the datepicker inputs dont work because are added dynamically after the datepicker plugin is loaded. Try to call the js plugin after you add a new input, maybe in the click event of link that add the inputs. Or try use this gem https://github.com/nathanvda/cocoon. By the way, what plugin you use for datepickers?
Related
Here's my select_tag item:
<%= select_tag :room_id, options_from_collection_for_select(Room.all, "id", "to_s") %>
Question: How can I get the selected value of a select_tag object on my form - while still on the form? (not using params[:room_id] inside the controller after it has been submitted)
In other words, I know I can use params[:room_id] in the controller once I've submitted the form. All of my searches about this question seem to tell me to just use params[:room_id]. What I need to do is simply to get the value of the select_tag item while still on the form and use it.
for example: <%= local_var = (value of select_tag) %>
Thanks,
You should be using a client side scripting language such as JavaScript or the jQuery library as shown below:
$( "#id_of_select_element" ).val();
Given a standard select code:
<%= f.select :type_name, [['Genomics','Genomics'],['Proteomics','Proteomics'],['Transcriptomics','Transcriptomics'],['Other','Other'] %>
Can someone explain how I would go about creating a text field when 'Other' is selected? So that the type_name can be something other than the options in the select?
I realise this is a simple question, but I haven't found a concise answer as of yet!
There are lots of ways to do this, but they all require JavaScript. The general approach I like is to put a hidden text field in the form, then attach a JavaScript event handler to the select tag that shows the field when the "Other" option is selected.
Here's a gist of the script I typically use for this. It handles the JavaScript binding using data attributes. Add the script to your assets, then put something like this in your form:
<%= f.select :type_name, [['Genomics','Genomics'],['Proteomics','Proteomics'],['Transcriptomics','Transcriptomics'],['Other','Other'] %>
<%= f.text_field :type_name_other, "data-depends-on" => "#object_type_name", "data-depends-on-value" => "Other" %>
where #object_type_name is the HTML id of your dropdown.
You need to create an attr_accessor on the model f is attached to (like type_name_other), add a text_field to the form below the select for type_name_other in a div that is initially hidden (in CSS: display:none), then create a javascript listener that detects when the select form has changed and if the selected ansser is "other" show the hidden field else hide it. You will then need to see if type_name_other has a value when processing the form and use it if so.
Background: My goal is for a view to display a list of "condition" has_many objects, which are themselves STI subclasses of a StateDescription. I want a user to be able to pick what type of state description they are from a drop down menu (which will conditionally display a different type of form, eventually)
Inside of my main forms, I am doing a nested form like this:
<%= f.fields_for :conditions do |e| %>
<li>
<%= e.select(:type, StateDescription.subclasses.collect{|x| x.to_s}, options_for_select(StateDescription.subclassSelectForms)) %>
<br>
<%= e.label :title %>
<%= e.text_field :title %>
</li>
<% end %>
This works just fine with the text field at the bottom there (I can change values and save them, etc). But when I try to do a select statement, it explodes.
Specifically, if I don't use e.select and just do:
<%= select(:type, StateDescription.subclasses.collect{|x| x.to_s}, options_for_select(StateDescription.subclassSelectForms)) %>
it renders just fine, but doesn't actually change any values as it is not associated with a model.
If I get rid of trying to have it display a value different than it submits and just do
<%= e.select(:type, StateDescription.subclasses.collect{|x| x.to_s}) %>
Then it works just fine(I can submit, the value is saved to the database, I can retrieve it, etc).
I can LEAVE it like this, but I had wanted to have my more human readable string display instead of a rails class thing (which might look like gibberish to a non-programmer end user).
So, my question is: Why do options_for_select break when nested and associated with a form, but dont' seem to when not associated with a form? Is it just a known bug? Am I doing something wrong?
Edit:
.subclasses is a standard rails calls which returns a list of subclasses for an object.
.subclassSelect forms goes through each subclass, and turns it into a hash of the form:
{subclass.to_s => subclass.human_readable_string} and compiles all of them into an array.
I know this array of hashes works, because if I do NOT put "e" on the front, it displays correctly and works "right" for what I have done (i.e. the subclass is returned correctly based on which human readable string I select from the drop down menu, but since it's not actually associated with any form, it doesn't get set in the controller).
I am new to RoR. I want to know how do we make a radio button default selected just first time while creating new record?
I tried
<%= radio_button_tag 'scheduler', 'now', true%> Now <br>
<%= radio_button_tag 'scheduler', 'future'%> Future<br>
It makes the first radio button (having value Now) checked but when i select second radio button (Future) and leave other mandatory fields blank on the form then again the first radio become selected instead of second.
How to resolve this.
Note: the field "scheduler" is just a virtual field on this form that will display another HTML containing a datetimepicker if "Future" option is selected and that datetimepicker field "schedule_date" is the actual field of the model. If option "Now" is posted then simply it will save the current date and time into the database table for that field "schedule_date". So i just have to show/hide an HTML by using these radio buttons.
When you say 'leave the mandatory fields blank' i guess you are submitting the form and getting the edit form back from the server with a warning flash? What I think you need to do here is instead of setting the Now field to true, you need to use a variable and set it to true on when creating a new form. Then when you submit the form to the server the controller's create method should look at the params hash, set the variable, and if the submission fails validation is should return the edit form with the Now variable set to false and the Future variable set to true
so in the create method of the controller you have something like
#now = params[:scheduler][:now]
in the new method of the controller you have:
#now = true
and in the view:
<%= radio_button_tag 'scheduler', 'now', #now%> Now <br>
<%= radio_button_tag 'scheduler', 'future', !#now %> Future<br>
This is true because you have set the first radio button to be selected by default. So when you select the second radio button and then refresh/submit the form, the page comes to its original position losing the previous selected second button.
This is just like when you enter the form fields and then refresh the form or come back again to the form after going back, you loss the data that you filled previously.
Solution:
I say get the checked radio button value and set it using jquery as-
$('input[name="myradios"]').change(function() {
alert($(this).val());
});
Try:
<%= radio_button_tag 'scheduler', 'now', true %> Now <br>
<%= radio_button_tag 'scheduler', 'future', params[:scheduler].eql?("future") %> Future<br>
In my form, I used the span tag like the following:
<%= content_tag :span, f.object.User, class: 'username' %>
It looks like the following in HTML after i selected the value:
<span class="user" style="">Antony</span>
The problem is id doesn't get the value to the database when we create a form. I don't know the exact problem is. I want to use this content tag instead of text_field to get the value.
Thanks.
When you submit an HTML form, the only values that get POSTed are those that are in input fields such as text fields, selects, checkboxes, buttons, etc. Content that is simply on the page -- in a span or not -- will not get posted back to the server. That isn't a Rails issue, it's just the way HTML works.
I'm not exactly sure what you're trying to do here, but a common approach when you want to display a value (not in an input box) and also post the value back with the form, is to both render the value on the page (in a span or however you want) and also add a hidden input field (hidden_field_tag) that also has the value in it.
Yeah, Jacob is correct. Better create a hidden field
<%= f.hidden_field :user, class: 'user' %>
<%= content_tag :span, f.object.User, class: 'username' %>
The first line get the value in it. I hope, Jacob answer would help you. :)