A better way to handle form submission?


#1

I am working on a project that requires hefty form field submissions of input fields and textareas. I have found it very exhausting to write the 50+ html fields with their associated attributes, then write the client submission method call including all 50+ fields, and then once again write the server submission method.

I have expedited this a little bit because I am handy with my keyboard short cuts. But all in all I have to address 150+ items. And to make things worse I have to almost replicate this on another “view”. I wanted to loop through the fields, and place them into the Meteor.method parameters. But I could not think of a way to do that without it turning into one long string.

To put the scenario into context, It is a listing app for boats. So the admin would come in and fill out the form for all the specs relating to the boat. This would be then be submitted and displayed where every necessary. Then there is another form with similar fields but to update that boats specs if there was a mistake or change.

Has anyone else had to address forms with lots of input/text fields?


#2

You could do that in (at least) two other ways:

  1. Pass a single object holding the fields.
  2. Put the fields into an array and use Meteor.apply instead of Meteor.call.

My preference would be the object, because parameters are then position independent and may be added to or removed without needing to maintain a picture of which parameter goes where.


#3

To build on what @robfallows said, I would do it as follows (uses jQuery, assumes that all your fields have a name attribute which match your field names):

// Fetch all textfield values
var data = {};
$('form#yourFormId input[type=text]').forEach(function(field) {
  data[field.name] = field.value;
});
Meteor.call("yourMethod", data, function(err, result) { ... });

Though an even better solution would be to use a different view layer, like Vue or ViewModel, which can handle binding your field values to a javascript object you can pass to your method for you.

Also make sure you’re using simple-schema for your collections which can make doing validations on your data easier by keeping all the validation logic in one place.


#4

To add to the previous comments: You can use some helpers for that. For example serializeJSON. There is already a package for this.


#5

Ah yea, these are good suggestions, I will give it a try between now and this weekend. Thanks guys!