@bleutzinn,
Three alternatives:
1. Using Twig
When searching for datasets
in the template folder of the Form plugin, I find a reference inside user/plugins/form/templates/forms/default/field.html.twig which is located inside block {% block input_attributes %}
.
When adding the following inside /user/plugins/fixfilefield/templates/forms/field.html.twig the attributes will be set correctly:
{% block input_attributes %}
{% if field.type == 'file' %}
{# Simple way of setting attributes #}
xxx="yyy"
{# Using the field.datasets property #}
{% set myNewKeyValue = {
'twigDataKey': 'twigDataValue'
} %}
{% set field = field|merge({ 'datasets': (field.datasets|default([]))|merge(myNewKeyValue) }) %}
{% endif %}
{{ parent() }}
{% endblock %}
When using the following field definition inside page form.md
:
...
fields:
uploads:
type: file
datasets:
formDefDataKey: formDefDataValue
The resulting HTML will be:
<input type="file" accept="image/*" class="form-input "
xxx="yyy" <-- from Twig
data-formdefdatakey="formDefDataValue" <-- from form definition
data-twigdatakey="twigDataValue" <-- from Twig
>
2. Using PHP to add field attributes:
Alternatively, without using any Twig you could simply use PHP:
public function onFormInitialized(Event $event)
{
$form = $event['form'];
$fields = $form->getFields();
foreach ($fields as $key => $field) {
if ($field['type'] === 'file') {
$fields[$key]['datasets']['phpKey'] = 'phpValue';
}
}
$form->setFields($fields);
}
Without any template file, this will generate (using the same form definition as above):
<input type="file" accept="image/*" class="form-input "
data-formdefdatakey="formDefDataValue" <-- from form definition
data-phpkey="phpValue" <-- From PHP
>
3. Using PHP to injecting object into HTML:
Since all you want is to pass meta data about the field into HTML to allow js to validate the form, you could also inject a PHP object into HTML using Asset Manager using inlineJs()
. Js can access the object and use it to validate the form.
I donāt really see the necessity to inject the meta data into the HTML <input> field itself. It only adds complexity: More complexity to inject and more the retrieve from DOM.