Symfony嵌入式表单和约束



>想象像这样的简单实体

class User {
  /**
   * @ORMEmbedded(class="Role")
   */
  protected $role;
}

和这样的表单类型

class UserType extends AbstractType
{
  /**
   * @param FormBuilderInterface $builder
   * @param array $options
   */
  public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('role', RoleType::class);
}
/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(
        array(
            'data_class' => 'XXXBundleEntityUser',
            'csrf_protection' => false,
        )
    );
}
}

和角色实体的角色类型窗体

/**
 * @ORMEmbeddable()
 */
class Role
{
    /**
     * @ORMColumn(type="string")
     * @AssertChoice(choices={"foo", "bar"})
     */
    private $name;
    /**
     * Role constructor.
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }
    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }
}
class RoleType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'XXXBundleEntityRole',
                'empty_data' => function (FormInterface $form) {
                    return new Role($form->get('name')->getData());
                },
            )
        );
    }
}

使用典型的表单>是有效的选择约束断言无法正常工作...实际上并未验证角色名称值。

我找到了Symfony3的解决方案

    /**
     * @ORMEmbedded(class="Role")
     * @AssertValid()
     */
    protected $role;

相关内容

  • 没有找到相关文章

最新更新