简体   繁体   English

Symfony2中同一实体上的不同验证规则

[英]Different validation rules on same entity in Symfony2

The admin will be able to edit the users of his website, but not the password. 管理员将能够编辑其网站的用户,但不能编辑密码。 So I've created this EditUserFormType : 所以我创建了这个EditUserFormType:

namespace CAPUserBundle\Form\Type;

use CAPShopAdminBundle\Repository\DiscountGridRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class EditUserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('email', EmailType::class);
        $builder->add('discountGrid', EntityType::class, array(
            'class' => 'CAPShopAdminBundle:DiscountGrid',
            'choice_label' => 'name',
            'placeholder' => '-- Aucune --',
            'required' => false,
            'query_builder' => function (DiscountGridRepository $r) {
                $qb = $r->createQueryBuilder('d');
                $qb->orderBy('d.name', 'ASC');
                return $qb;
            },
            'attr' => array("autocomplete" => "off"),
        ));
        $builder->add('isActive', ChoiceType::class, array(
            'choices' => array(
                'Actif' => '1',
                'Désactivé' => '0'
            ),
        ));
        $builder->add('name', TextType::class);
        $builder->add('firstname', TextType::class);
        $builder->add('company', TextType::class);
        $builder->add('address', TextType::class);
        $builder->add('postcode', TextType::class);
        $builder->add('city', TextType::class);
        $builder->add('phone', TextType::class);
        $builder->add('fax', TextType::class);

        $builder->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'CAPUserBundle\Entity\User',
        ]);
    }

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

But when i validate the form, there is an error with the plainPassword field from my User entity. 但是,当我验证表单时,我的User实体的plainPassword字段出现错误。

This value should not be blank.     edit_user   
Symfony\Component\Validator\ConstraintViolation

Object(Symfony\Component\Form\Form).data.plainPassword = 

Indeed, there is a NotBlank validation constraint on it in order to force the user to set the password when he is registering. 确实,上面有一个NotBlank验证约束,以强制用户在注册时设置密码。

My question is : how can I bypass this constraint for editing my User ? 我的问题是:如何绕过此约束来编辑用户? The password field isn't present on the EditUserFormType, so the plainPassword is useless. 密码字段在EditUserFormType上不存在,因此plainPassword是无用的。 But I'm stuck because I use the same User Entity where is set the NotBlank value. 但是我被卡住了,因为我在设置NotBlank值的地方使用了相同的用户实体。

For the moment, I force the plainPassord field with : 目前,我用以下命令强制plainPassord字段:

$user->setPlainPassword('Ap@ssw0rd');

But this is an awful way to bypass the constraint... 但这是绕过约束的可怕方法...

Use Validation Groups for discriminate validation rules. 使用验证组来区分验证规则。

In this case plainPassword in required for registration, and not required for editing. 在这种情况下,plainPassword需要注册,而编辑则不需要。

So, set "registration" group for NotBlank constraint. 因此,为NotBlank约束设置“注册”组。

And I chose a completely different approach, renouncing the annotation-like validation rules in data models and using the constraints in the forms classes instead. 然后,我选择了一种完全不同的方法,即在数据模型中放弃类似注释的验证规则,而在表单类中使用约束。 For example: 例如:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $dateConstraintFrom = new Date();
    $notBlankDateFrom = new NotBlank();

    $builder->add('date_from', TextType::class, array(
        'required' => true,
        'label' => 'bookform.place.date_from',
        'constraints' => array($notBlankDateFrom, $dateConstraintFrom),

        'attr' => array(
            'placeholder' => 'bookform.place.date_from',
            'id' => 'bookform_place_date_from',
            'required' => 'required',
        ),
    ));
    ...........
 }

I am used to this way of doing things and it's much more comfortable than annotations and validation groups. 我已经习惯了这种处理方式,它比注释和验证组舒服得多。

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

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