Reading Back a Template
In the last month I started to massively review the internals of Larastrap, in the aim to deliver a 1.0 release within the next weeks (just in time to celebrate the first 5000 downloads from Packagist). And I've began to implement a bizarre idea.
In the usual PHP web application, you create an HTML form in a template and, in the endpoint function used for the POST submission, you retrieve the informations filled by the user, using name
attributes as a map to assign to each value the proper meaning (and providing proper validation). View and Controller share no informations about the data model rappresented by the first and manipulated by the second.
But creating a Larastrap Form, and assigning it an Eloquent Model, each HTML input can have an explicit semantic, defined by his name (matching the name of the model's attribute) and type (a text input, a checkbox, a select input referring a Collection of related Eloquent Models...). This is used to automatically fill the inputs with the proper values directly read from the model, so, why not using the same semantics to automatically reassign the submitted values back to each named attribute in the Model?
The initial implementation can be summarized as:
- the code of each Blade Components implementing each input node into a form also creates a basic rappresentation of the node itself, including his name, his type, his validation rules and a few other things
- this rappresentation is appended to a structure representing the whole form, serialized in JSON, stored in the current Session, and labelled by a random identifier which is then appended (dynamically and transparently) to the form's itself into an hidden input
- when the form is submitted, it is possible to retrieve the previously saved data model and match it to the incoming request, applying all the defined validation rules and re-assigning back values from the request to the initial model (or to a new instance of the defined Model class)
The idea to build HTML forms from data structures is not new at all (probably the most widely adopted implementation is Symfony Forms), but it may be new the purpose to implicitely create such a data structure starting from the template instead of just rendering the form in some default layout which usually doesn't matches client's expectations or designers' directives.
Actually the whole implementation is in a development branch of the Larastrap's repository and I'm testing it in a few projects to see how it performs and how it applies in real-world conditions. Until now, I've managed to have a single Controller endpoint to both store and update models of any given type (the Form itself knows if it was rendered on an existing instance or not) and often that endpoint consists of three lines of code:
$instance = LarastrapStack::autoreadSave($request, MyModel::class);
$instance->save();
return redirect()->route('mymodelcontroller.index');