An Array as User Interface
Generating forms and panels dynamically, from a parametric set of contextual informations defining if it must appear a text input or a numeric one, is not a new thing. But with Larastrap, I think I've reached a new level.
Right now I'm working on a large project where many different kind of entities interact with each other in many different ways, and to build - for example - the form to create a new Quote for a Service, each kind of Service declares which possible informations are to be asked to the user (and have to be rappresented in the related web form). This is actually done with an abstract function enforced in the core Service class, and each implementation returns an array of Larastrap Custom Elements where can arbitrarily push any kind of element, eventually differing not only due the Service type but also each specific instance and context and relations (e.g. a Service provided to a specific kind of Client may require some more data).
The library provides to then convert each of them in a properly formatted HTML node.
So, given - in each Service implementation - a function like
public function dataForQuotes()
{
$ret = [
'total' => [
'extends' => 'price',
'quotingType' => 'actual',
'params' => [
'label' => 'Price',
]
],
'royalty' => [
'extends' => 'percentable-price',
'quotingType' => 'royalty',
'params' => [
'label' => 'Royalty',
'attributes' => [
'typename' => 'royalty_type',
],
]
],
];
if ($this->someCondition()) {
$reference = [
'extends' => 'price',
'params' => [
'label' => 'Extra',
]
];
$ret['reference'] = $reference;
}
return $ret;
}I can explode the given array - in this case, and in many other - with a single generic Blade template to be included:
@foreach($fields as $extra_attribute_name => $extra_attribute_meta)
@php
$params = $extra_attribute_meta['params'] ?? [];
$params = array_merge([
'name' => $extra_attribute_name,
], $params);
$widget = sprintf('larastrap::%s', $extra_attribute_meta['extends']);
@endphp
<x-dynamic-component :component="$widget" :params="$params" />
@endforeach
Note that "price" and "percentable-price" here are Custom Elements, got from the examples' page.
Right now, I'm generating with this method also the web page used by the Client to reply to the Quote. Which hosts not only different HTML input fields, but also different downloadable documents. Described as a (parametric, of course) array of Larastrap Links, formatted into a Bootstrap Card (which is another Custom Element, more exactly a Composite).
This thing of parametric interfaces in getting out of hand...