简体   繁体   English

Symfony / Twig:如何将其他数据传递给表单?

[英]Symfony/Twig: how to pass additional data to a form?

I'm looking for a way to manage all the form data within MyFormType.php . 我正在寻找一种方法来管理MyFormType.php所有表单数据。 So far I've the label and placeholder , but I'd like to store an additional string, eg for "more details" . 到目前为止,我有labelplaceholder ,但我想存储一个额外的字符串,例如“更多细节”

AppBundle\\Form\\Type\\MyFormType.php 的appbundle \\表格\\型号\\ MyFormType.php

// ...
$builder->add('fieldname', TextType::class, [
    'label' => 'My label',
    'attr'  => ['placeholder' => 'My placeholder'],       
    'additionalData' => ['info' => 'More information] // <- ???      
]);
// ...

myForm.html.twig myForm.html.twig

Label: {{form_label(form.fieldname)}} 
Textfield: {{form_widget(form.fieldname)}}  
Info: {{form_additionalData(form.fieldname, 'info')}}  {# ??? #}

I was thinking about passing the data via an data-* -attribute like: 我正在考虑通过data-* -attribute传递数据,如:

// ...
'attr' => ['data-info' => 'more information']
// ...

But how to read the data in a good way, without buggy workarounds? 但是如何以一种好的方式读取数据,而没有错误的解决方法?

Any best/good practise for this issue? 这个问题的最佳/良好做法是什么?

Thanks in advance! 提前致谢!

Good practice would be to create a FormType for your needs and configure necessary options for it. 好的做法是根据需要创建FormType并为其配置必要的选项。

class YourType extends AbstractType
{
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'add_info'  => "",
        ));
    }


    public function buildView(FormView $view, FormInterface $form, array $options)
    {
       $view->vars = array_replace($view->vars, array(
            'add_info' => $options['add_info'],
        ));
    }

    public function getBlockPrefix()
    {
        return 'your_type';
    }


    public function getParent() 
    {
        return TextType::class;
    }
}

Then 然后

$builder->add('fieldname', YourType::class, [
    'label' => 'My label',
    'attr'  => ['placeholder' => 'My placeholder'],       
    'add_info' => 'More information'
]);

And then make a widget 然后制作一个小部件

{% block your_type_widget %}
    {% spaceless %}
        {{ add_info }} 
            ... other code
    {% endspaceless %}
{% endblock %}

By using a form type extension for that probably is a way if it's a common use case in your application: 通过使用表单类型扩展 ,如果它是应用程序中的常见用例,则可能是一种方法:

# src/AppBundle/Form/Extension/FormTypeExtension.php

class FormTypeExtension extends AbstractTypeExtension
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        foreach ($options['extra_data'] as $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 your 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 to read the data in a good way, without buggy workarounds? 但是如何以一种好的方式读取数据,而没有错误的解决方法?

In some JavaScript context by using jQuery example: 在一些JavaScript上下文中使用jQuery示例:

var data = $('#form_name').data();

// all data values are converted to JSON automatically
alert(data.foo); // display: bar
alert(data.baz.name); // display: john

B. B.

I see that none of the answers show a Twig solution, so I wanted to show a Twig answer in case you want to use that. 我看到没有答案显示Twig解决方案,所以我想显示一个Twig答案,以防你想要使用它。 The format for a form_label verses a form_widget are different, so keep that in mind when you code. form_labelform_widget的格式不同,因此在编码时请记住这一点。

I don't know of any form_additionalData rending specification. 我不知道任何form_additionalData规范。 See the reference here . 请参阅此处参考 But instead there is just "form_label, form_errors, and form_widget" that can be used. 但相反,只有“form_label,form_errors和form_widget”可以使用。

In my example below, I'll show "form_label" and "form_widget" for your reference (with a little variety). 在下面的示例中,我将显示“form_label”和“form_widget”供您参考(有一点变化)。 This works, I tried it out: 这有效,我试了一下:

Label: {{ form_label(form.fieldname,null,{
    'label_attr':{
        'id':'my_label_id',
        'class':'my_label_class',
        'data-info':'my label information'
    }
}) }}
Textfield: {{ form_widget(form.fieldname,{
     'attr':{
        'class':'my_text_field_class',
        'data-info':'my-text-field information'
     }
}) }}

Let me know if you have questions. 如果您有疑问,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM