Cleaning Up Form Input with Transpose

Cleaning Up Form Input with Transpose

This post is adapted from my upcoming book, “Refactoring to Collections”. Learn more about the book and subscribe to updates here.

Dealing with arrays in form submissions is a pain in the ass.

Imagine you need to build a page that allows users to add multiple contacts at once. If a contact has a name, email, and occupation, ideally the incoming request would look something like this:

[ 'contacts' => [ [ 'name' => 'Jane', 'occupation' => 'Doctor', 'email' => '', ], [ 'name' => 'Bob', 'occupation' => 'Plumber', 'email' => '', ], [ 'name' => 'Mary', 'occupation' => 'Dentist', 'email' => '', ], ], ];

The problem is that crafting a form that actually submits this format is surprisingly complicated.

If you haven’t had to do this before, you might think you can get away with something like this, using just a pinch of JavaScript to duplicate the form fields while keeping all of the field names the same:

Originally published at