php - Symfony/Twig: how to pass additional data to a form? -
i'm looking way manage form data within myformtype.php
. far i've label
, placeholder
, i'd store additional string, e.g. "more details".
appbundle\form\type\myformtype.php
// ... $builder->add('fieldname', texttype::class, [ 'label' => 'my label', 'attr' => ['placeholder' => 'my placeholder'], 'additionaldata' => ['info' => 'more information] // <- ??? ]); // ...
myform.html.twig
label: {{form_label(form.fieldname)}} textfield: {{form_widget(form.fieldname)}} info: {{form_additionaldata(form.fieldname, 'info')}} {# ??? #}
i thinking passing data via data-*
-attribute like:
// ... 'attr' => ['data-info' => 'more information'] // ...
but how read data in way, without buggy workarounds?
any best/good practise issue?
thanks in advance!
by using form type extension way if it's common use case in application:
# src/appbundle/form/extension/formtypeextension.php class formtypeextension extends abstracttypeextension { public function buildview(formview $view, forminterface $form, array $options) { foreach ($options['extra_data'] $name => $data) { $dataname = sprintf('data-%s', $name); $view->vars['attr'][$dataname] = json_encode($data); } } public function configureoptions(optionsresolver $resolver) { $resolver->setdefaults(array('extra_data' => array())); $resolver->setallowedtypes('extra_data', 'array'); } public function getextendedtype() { return formtype::class; } }
register form type extension:
# app/config/services.yml services: app.form.extension.form_type: class: appbundle\form\extension\formtypeextension tags: - { name: form.type_extension, extended_type: symfony\component\form\extension\core\type\formtype }
if:
$form->add('name', texttype::class, array( 'extra_data' => array( 'foo' => 'bar', 'baz' => array('name' => 'john'), ), ));
then:
<input type="text" id="form_name" name="form[name]" data-foo=""bar"" data-baz="{"name": "john"}"/>
but how read data in way, without buggy workarounds?
in javascript context using jquery example:
var data = $('#form_name').data(); // data values converted json automatically alert(data.foo); // display: bar alert(data.baz.name); // display: john
Comments
Post a Comment