I am trying to wrap my head around how to allow a user to create custom forms with all the field types. If there is a gem that would be great, but I cannot seem to find one anywhere.
So I have a DB setup like this which:
t.integer :form_id
t.string :name
t.string :hint
t.integer :position
t.string :field_type
t.boolean :required
t.integer :size
t.boolean :multiple
t.text :values
t.timestamps
And this is pretty much where I am. I cant think of how to iterate thru the field_type and return the values, as well as associate them with forms actually being filled out.
Thanks
I assume you have some kind of Form
model, and then some kind of Field
model, and a Form has_many :fields
. Correct?
Building the form is than quite straightforward: retrieve the form, iterate over all the fields, and depending on the type, render the correct code. If you use something like formtastic or simple_form the code is pretty straightforward.
But to make it work, inside your controller you will have to create a dummy object, that has a getter and setter for all fields. You could use a simple hash for this, or OpenStruct (better). While iterating over the fields set the hash with empty or default values.
I think you also want to save the results of a form? I think the easiest way is to use a model like this
t.form_id :integer
t.fields_data :text
And store the entered data in the text-field in e.g. json or something. You could also do something like
class FormData
belongs_to :form
end
class FormDataField
belongs_to :form_data
belongs_to :form_field
end
while this is the cleanest (you can query on values of filled in fields for a certain form), it is maybe too much of an overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With