表单在symfony2中始终有效

时间:2014-10-29 19:24:41

标签: php validation symfony symfony-forms

我有一个带有此验证的表单:

# ITW/UserBundle/Resources/config/validation.yml

ITW\UserBundle\Entity\User:
    properties:
        name:
            - NotBlank: ~
            - Length: { min: 800 }

我正在检查这样的表格:

// ITW/UserBundle/Controller/UserController.php

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

    $form->handleRequest($request);

    if ($form->isValid()) {
        echo "valid!";
    }

并且在config.yml中验证是:

validation:      { enabled: true }

但是,当我提交包含空name字段的表单时,$form->isValid()始终返回True

我无法弄清楚出了什么问题! 我确定validation.yml正确加载(因为当我使用无效字段名称symfony时会出现异常)

问题出在哪里?


Symfony版本为2.5.6&我也试过2.5.5
我还尝试使用getters字段name的约束目标,并获得相同的结果。


我的UserType是:

namespace ITW\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use ITW\UserBundle\Entity\User;

class UserType extends AbstractType
{
    public function __construct(){}

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('name','text',array('required'  => true,'label'=>'name'))
        ->add('family','text',array('required'  => true,'label'=>'family'))
        ->add('tels','collection', array('required'  => false,'prototype'=>true,'type'=> 'text','allow_add'=>true,'delete_empty'=>true,'label'=>'Tel'))
        ->add('username','text',array('required'  => true,'label'=>'username'))
        ->add('password','password',array('required'  => true,'label'=>'password'));

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ITW\UserBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'itw_userbundle_user';
    }
}

1 个答案:

答案 0 :(得分:0)

只是为了澄清,如果您尚未从validation文件中删除部分form,则配置config.ymlenabled by default

framework:
    form: ~