Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails fields_for with ajax

I am building a dynamic form builder.. And i have a problem which i can't seem to fix.

So i have a db table called "forms" forms can have "fields"..

The problem is that when a user creates a new 'field' (click add-field) then it should ajax the new field for .. that field.

The problem is that i can't just do something like this:
<%= Form.fields_for Field.new do |field| %>
  <%= field.text_field :name%>
<% end %>

Does anybody have an idea? Yes i watch railscasts, yes i googled, yes i found the "complex-forms' repo on github.

But no luck (yet)

like image 508
heldopslippers Avatar asked Dec 06 '25 12:12

heldopslippers


1 Answers

If you want an all javascript approach (instead of calling your server to produce the field names) then basically you just need to increment the field names for any new fields.

For example, if you have

class Form < ActiveRecord::Base
  has_many :fields
  accepts_nested_attributes_for :fields

and the HTML in the form has an input field that has something like

<label for="form_fields_attributes_0_name">
<input id="form_fields_attributes_0_name" name="form[fields_attributes][0][name]" type="text" />

then you need to write some javascript to make it look like

<label for="form_fields_attributes_1_name">
<input id="form_fields_attributes_1_name" name="form[fields_attributes][1][name" type="text" />

You can do something like

$('#form_fields_attributes_1_name').attr('id').split('_');

and

$('#form_fields_attributes_1_name').attr('name').split(/\]\[/);

to get at those numbers.

Here's an example which is refactored here.

like image 116
monocle Avatar answered Dec 09 '25 19:12

monocle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!