繁体   English   中英

Symfony2:如何在自定义复合表单类型上使用约束?

[英]Symfony2: How to use constraints on custom compound form type?

这是一个我一直在讨厌的问题。 请知道我还不是Symfony2专家,所以我可能在某个地方犯了一个菜鸟错误。

Field1:标准Symfony2 text字段类型

Field2:自定义字段类型compound字段,带有text字段+ checkbox字段)

预习

我的目标:将约束添加到autoValue字段以处理autoValue's text input child

约束不起作用的原因可能是因为NotBlank期望一个字符串值,并且此表单字段的内部数据是一个数组array('input'=>'value', 'checkbox' => true) 此数组值将转换回具有自定义DataTransformer的字符串。 但我怀疑在根据已知约束验证字段后会发生这种情况。

正如您在注释代码中看到的那样,我已经能够在文本输入上获得约束,但是只有当硬编码到autoValue的表单类型中时,我才能根据主要字段的约束进行验证。

控制器和字段的我(简化)示例代码:

控制器代码

设置快速表单以进行测试。

<?php
//...
// $entityInstance holds an entity that has it's own constraints 
// that have been added via annotations

$formBuilder = $this->createFormBuilder( $entityInstance, array(
    'attr' => array(
        // added to disable html5 validation
        'novalidate' => 'novalidate'
    )
));

$formBuilder->add('regular_text', 'text', array(
    'constraints' => array(
        new \Symfony\Component\Validator\Constraints\NotBlank()
    )
));

$formBuilder->add('auto_text', 'textWithAutoValue', array(
    'constraints' => array(
        new \Symfony\Component\Validator\Constraints\NotBlank()
    )
));

TextWithAutoValue源文件

SRC /我的/分量/表/类型/ TextWithAutoValueType.php

<?php

namespace My\Component\Form\Type;

use My\Component\Form\DataTransformer\TextWithAutoValueTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class TextWithAutoValueType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('value', 'text', array(
            // when I uncomment this, the NotBlank constraint works. I just
            // want to validate against whatever constraints are added to the
            // main form field 'auto_text' instead of hardcoding them here
            // 'constraints' => array(
            //     new \Symfony\Component\Validator\Constraints\NotBlank()
            // )
        ));

        $builder->add('checkbox', 'checkbox', array(
        ));

        $builder->addModelTransformer(
            new TextWithAutoValueTransformer()
        );
    }

    public function getName()
    {
        return 'textWithAutoValue';
    }
}

SRC /我的/分量/表格/ DataTransformer / TextWithAutoValueType.php

<?php

namespace My\Component\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class TextWithAutoValueTransformer 
    implements DataTransformerInterface
{
    /**
     * @inheritdoc
     */
    public function transform($value)
    {
        return array(
            'value'    => (string) $value,
            'checkbox' => true
        );
    }

    /**
     * @inheritdoc
     */
    public function reverseTransform($value)
    {
        return $value['value'];
    }
}

SRC /我的/ ComponentBundle /资源/配置/ services.yml

parameters:

services:
    my_component.form.type.textWithAutoValue:
        class: My\Component\Form\Type\TextWithAutoValueType
        tags:
            - { name: form.type, alias: textWithAutoValue }

SRC /我的/ ComponentBundle /资源/视图/表格/ fields.html.twig

{% block textWithAutoValue_widget %}
    {% spaceless %}

    {{ form_widget(form.value) }}
    {{ form_widget(form.checkbox) }}
    <label for="{{ form.checkbox.vars.id}}">use default value</label>

    {% endspaceless %}
{% endblock %}

我一直在阅读docs和google几个小时,无法弄清楚如何复制,绑定或引用构建此表单时添加的原始约束。

- >有谁知道怎么做到这一点?

- >奖励积分; 如何启用已添加到主窗体绑定实体的约束? (通过实体类的注释)

PS

对不起它成了这么长的问题,我希望我成功地解决了我的问题。 如果没有,请向我询问更多详情!

我建议您先阅读有关验证文档

我们可以做到的是验证主要发生在类而不是表单类型上。 那是你忽略的。 你需要做的是:

  • 要为TextWithAutoValueType创建一个数据类,例如,名为src / My / Bundle / Form / Model / TextWithAutoValue 它必须包含名为textcheckbox的属性及其setter / getter;
  • 将此数据类与表单类型相关联。 为此,您必须创建TextWithAutoValueType :: getDefaultOptions()方法并填充data_class选项。 到这里获取有关此方法的更多信息;
  • 为您的数据类创建验证。 您可以使用注释或Resources / config / validation.yml文件。 您必须将它们与类的属性相关联,而不是将约束与表单的字段相关联:

validation.yml

src/My/Bundle/Form/Model/TextWithAutoValue:
    properties:
        text:
            - Type:
                type: string
            - NotBlank: ~
        checkbox:
            - Type:
                type: boolean

编辑:

我假设您已经知道如何在另一个表单中使用表单类型。 定义验证配置时,您可以使用一个非常有用的东西,称为验证组 这是一个基本的例子(在validation.yml文件中,因为我不太熟悉验证注释):

src/My/Bundle/Form/Model/TextWithAutoValue:
    properties:
        text:
            - Type:
                type: string
                groups: [ Default, Create, Edit ]
            - NotBlank:
                groups: [ Edit ]
        checkbox:
            - Type:
                type: boolean

有一个groups参数可以添加到每个约束。 它是一个包含验证组名称的数组。 请求对对象进行验证时,您可以指定要验证的组集。 然后,系统将在验证文件中查找应该应用的约束。

默认情况下,“默认”组在所有约束上设置。 这也是执行常规验证时使用的组。

  • 您可以通过设置validation_groups参数(字符串数组 - 验证组的名称 ,在MyFormType :: getDefaultOptions()中指定特定表单类型的默认组,
  • 将表单类型附加到另一个表单类型时,在MyFormType :: buildForm()中 ,您可以使用特定的验证组。

当然,这是所有表单类型选项的标准行为。 一个例子:

$formBuilder->add('auto_text', 'textWithAutoValue', array(
    'label' => 'my_label',
    'validation_groups' => array('Default', 'Edit'),
));

至于使用不同的实体,您可以使用与堆积形式相同的架构来堆积数据类。 在上面的示例中,使用textWithAutoValueType的表单类型必须具有data_class,该data_class具有'auto_text'属性和相应的getter / setter。

在验证文件中, 有效约束将能够级联验证。 具有Valid的属性将检测属性的类,并将尝试为此类查找相应的验证配置,并将其应用于相同的验证组:

src/My/Bundle/Form/Model/ContainerDataClass:
    properties:
        auto_text:
            Valid: ~ # Will call the validation conf just below with the same groups

src/My/Bundle/Form/Model/TextWithAutoValue:
    properties:
        ... etc

如下所述https://speakerdeck.com/bschussek/3-steps-to-symfony2-form-mastery#39 (幻灯片39)由Bernhard Schussek(symofny表格扩展的主要贡献者),变压器应该永远不会改变信息,但只改变其代表性。

添加信息(复选框'=> true),你做错了什么。

在编辑中:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('value', 'text', $options);

    $builder->add('checkbox', 'checkbox', array('mapped'=>false));

    $builder->addModelTransformer(
        new TextWithAutoValueTransformer()
    );
}

暂无
暂无

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

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