php - 具有非映射字段的 Symfony 3 唯一约束

标签 php symfony

我正在使用 Symfony 3,我正在处理没有映射实体的表单,data_class => null 如下:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', null, ['label' => 'user.edit.label.firstname'])
            ->add('lastname', null, ['label' => 'user.edit.label.lastname'])
            ->add('email', EmailType::class, ['label' => 'common.email', ])
            ->add('state', ChoiceType::class, [
                'label' => 'common.state',
                'choices' => array_flip(CompanyHasUser::getConstants())
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null,
            'translation_domain' => 'messages'
        ));
    }

那么有了这个,我怎样才能限制我的字段 'email' 是唯一的?我需要在我的实体用户 (attribute=email) 中进行检查。

有什么想法吗?

最佳答案

如果没有映射的实体,您将不得不检查数据库。最简单的方法是将 UserRepository 注入(inject)您的表单类。 ( Inject a repository link .)

在您的存储库中,创建一个查询方法以确保电子邮件不存在。这可以很容易地返回 bool 值 true 或 false。

在您的表单中,创建自定义约束回调。

public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'         => null,
            'translation_domain' => 'messages',
            'constraints'        => [
                new Callback([
                    'callback' => [$this, 'checkEmails'],
                ]),
            ]))
        ;
    }

并使用 UserRepo 在同一个表单类中添加回调函数。

/**
 * @param $data
 * @param ExecutionContextInterface $context
 */
public function checkEmails($data, ExecutionContextInterface $context)
{
    $email = $data['email'];
    if ($this->userRepository->checkEmail($email)) {
        $context->addViolation('You are already a user, log in.');
    }
}

另见 blog post on callback constraints without an entity .

关于php - 具有非映射字段的 Symfony 3 唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238703/

相关文章:

php - 用于 PHP 的 SQL Builder,具有 JOIN 支持?

php - 生成 PHP 代码(来自 Parser Tokens)

php - key 中的 AES-128 UTF-8 字符 (iOS ↔ PHP)

php - 如何在 PHP 中使用左连接数据将数据从映射器保存到实体

php - 学说 2 : How to search for an entity by its association's value?

PHP 5.2 和 PHP 5.3 在同一个 Apache (Debian) 上的 vHosts 中并行运行?

symfony - Composer 更新 - 无法在 http ://packagist. org 中加载包 shopware/shopware:

symfony - 使用symfony 2的快速邮件程序,收到了一封电子邮件,但在电子邮件中收到了不必要的回复

php - 在 Twig 中显示 token 用户名 symfony2

php - 在 OS X 10.10 Yosemite 上设置 Symfony2 和 Postgresql?