Symfony,用户的约束

伊琳娜·温特

再会!我刚开始自学 Symfony。

我正在制作一个新闻门户。管理员可以从 Excel 文件下载新闻。我正在将文件转换为关联数组。例如:

[ 'Title' => 'Some title',
  'Text'  => 'Some text',
  'User'  => '[email protected]',
  'Image' => 'https://loremflickr.com/640/360'
]

接下来,我想将此数组发送到表单并使用“约束”来验证它。“标题”、“文本”、“图像”字段没有问题。我不知道如何正确检查“用户”字段。文件中的用户正在提交电子邮件,但我想检查数据库中是否存在具有该电子邮件的用户。

新闻导入类型

    class NewsImportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['min' => 256])
                ],
            ])
            ->add('text', TextareaType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['max' => 1000])
                ],
            ])
            ->add('user', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Email(),
                ],
            ->add('image', TextType::class, [
                'constraints' =>
                [
                    new NotBlank(),
                    new Length(['max' => 256]),
                    new Url()
                ],
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true,
            'data_class' => News::class,
        ]);
    }
}

实体用户和新闻通过一对多关系连接。

我正在考虑使用 ChoiceType 并以某种方式调用 UserRepository,但我不明白如何正确应用它。

请告诉我如何正确地为“用户”字段编写“约束”。谢谢!

老板

创建自定义约束通过这种方式,它可以以您想要检查用户的任何其他形式重复使用。

在您的项目中创建一个新文件夹,src/Validator然后将这两个文件放在那里。

约束

// src/Validator/userAccountExists.php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;

class UserAccountExists extends Constraint
{
    public $message = 'User account does\'t exists. Please check the email address and try again.';
}

验证者

// src/Validator/userAccountExistsValidator.php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User;

class UserAccountExistsValidator extends ConstraintValidator
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function validate($email, Constraint $constraint)
    {
        if (!$constraint instanceof UserAccountExists) {
            throw new UnexpectedTypeException($constraint, UserAccountExists::class);
        }

        if (null === $email || '' === $email) {
            return;
        }

        if (!is_string($email)) {
            throw new UnexpectedValueException($email, 'string');
        }

        if (!$this->userExists($email)) {
            $this->context->buildViolation($constraint->message)->addViolation();
        }
    }

    private function userExists(string $email): bool
    {
        $user = $this->entityManager->getRepository(User::class)->findOneBy(array('email' => $email));

        return null !== $user;
    }
}

在您的表单中,您现在可以使用验证器

->add('user', TextType::class, [
    'constraints' =>
        [
            new NotBlank(),
            new Email(),
            new UserAccountExists(),
        ],

记得添加use App\Validator\UserAccountExists;到您的表单中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章