Cleaning Up Form Input with Transpose
Adam Wathan has written a nice tutorial about cleaning up form input with Transpose.
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' => '[email protected]', ], [ 'name' => 'Bob', 'occupation' => 'Plumber', 'email' => '[email protected]', ], [ 'name' => 'Mary', 'occupation' => 'Dentist', 'email' => '[email protected]', ], ], ];
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:
<form method="POST" action="/contacts"> <div> <label> Name <input name="contacts[][names]"> </label> <label> Email <input
Link: