Symfony2 - 验证不适用于嵌入式表单类型 [英] Symfony2 - Validation not working for embedded Form Type

查看:38
本文介绍了Symfony2 - 验证不适用于嵌入式表单类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结合了两个实体(用户和个人资料)的表单.

I have a form that combines two entities (User and Profile).

验证似乎对来自用户实体的表单的第一部分起作用,并且是表单的基础.

Validation seems to work on the first part of the form that comes form the User Entity and is the basis of the form.

ProfileType 包含在 UserType 中.表单正确呈现并显示正确的信息,因此它似乎已正确连接到 Profile 实体.只是 ProfileType 上的验证被破坏了.

The ProfileType is included inside the UserType. The form renders correctly and displays the correct information, so it seems it is properly connected to the Profile entity. It's just the validation that is broken on the ProfileType.

知道为什么一部分会验证而另一部分不会吗?

Any idea as to why one part would validate and the other wouldn't?

代码如下:

验证.yml

DEMODemoBundleEntityUserProfile:
    properties:
        address1:
            - NotBlank: { groups: [profile] }
        name:
            - NotBlank: { groups: [profile] }
        companyName:
            - NotBlank: { groups: [profile] }

DEMODemoBundleEntityUserUser:
    properties:
        username:
            - NotBlank:
                groups: profile
                message: Username cannot be left blank.
        email:
            - NotBlank:
                groups: profile
                message: Email cannot be left blank
            - Email:
                groups: profile
                message: The email "{{ value }}" is not a valid email.
                checkMX: true
        password:
            - MaxLength: { limit: 20, message: "Your password must not exceed {{ limit }} characters." }
            - MinLength: { limit: 4, message: "Your password must have at least {{ limit }} characters." }
            - NotBlank: ~

用户类型.php

namespace DEMODemoBundleFormTypeUser;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormCallbackValidator;
use SymfonyComponentFormFormBuilder;
use SymfonyComponentFormFormError;

use DEMODemoBundleFormTypeUserProfileType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('username');
        $builder->add('email');
        $builder->add('profile', new ProfileType());
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'DEMODemoBundleEntityUserUser',
            'validation_groups' => array('profile')
        );
    }

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

ProfileType.php

ProfileType.php

namespace DEMODemoBundleFormTypeUser;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormCallbackValidator;
use SymfonyComponentFormFormBuilder;
use SymfonyComponentFormFormError;

class ProfileType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name');
        $builder->add('companyName', null, array('label' => 'Company Name'));
        $builder->add('address1', null, array('label' => 'Address 1'));
        $builder->add('address2', null, array('label' => 'Address 2'));
        $builder->add('city');
        $builder->add('county');
        $builder->add('postcode');
        $builder->add('telephone');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'DEMODemoBundleEntityUserProfile',
        );
    }

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

控制器

$user = $this->get('security.context')->getToken()->getUser();

        $form = $this->createForm(new UserType(), $user);

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);

            if ($form->isValid()) {
                // Get $_POST data and submit to DB
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($user);
                $em->flush();

                // Set "success" flash notification
                $this->get('session')->setFlash('success', 'Profile saved.');
            }

        }

        return $this->render('DEMODemoBundle:UserDashboard:profile.html.twig', array('form' => $form->createView()));

推荐答案

我花了很长时间搜索,发现它正在将 'cascade_validation' => true 添加到 setDefaults() 修复它的父类型类中的数组(如线程中已经提到的).这会导致实体约束验证在表单中显示的子类型中触发.例如

I spent an age searching and found that it was adding 'cascade_validation' => true to the setDefaults() array in my parent type's class that fixed it (as mentioned already in the thread). This causes the entity constraint validation to trigger in the child types shown in the form. e.g.

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(            
        ...
        'cascade_validation' => true,
    ));
}

对于集合,还要确保将 'cascade_validation' => true 添加到表单上集合字段的 $options 数组.例如

For collections, also make sure to add 'cascade_validation' => true to the $options array for the collection field on the form. e.g.

$builder->add('children', 'collection', array(
    'type'         => new ChildType(),
    'cascade_validation' => true,
));

这将在集合中使用的子实体中进行 UniqueEntity 验证.

This will have the UniqueEntity validation take place as it should in the child entity used in the collection.

这篇关于Symfony2 - 验证不适用于嵌入式表单类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆