简体   繁体   English

具有数据库连接但没有实体的Symfony2自定义验证

[英]Symfony2 Custom Validation with DB connection but no Entity

I'm simply trying to validate a form (with no entity attached) with one field "username". 我只是在尝试验证具有一个字段“用户名”的表单(不附加任何实体)。 I want to check if the username exists or not. 我想检查用户名是否存在。 If it doesn't a proper message has to be displayed at form errors level (or form field errors level, I don't care that much). 如果不是正确的消息,则必须在表单错误级别(或表单字段错误级别,我不在乎)中显示。

Here is the relevant part of my controller: 这是我的控制器的相关部分:

$formGlobalSearch=$this->createFormBuilder()
->add('username', 'text', array('constraints' => new UsernameExists()))
->add('role', 'choice', array('choices' => $rolesListForForm,'required' => false, 'placeholder' => 'Choose a role', 'label' => false, ))
->add('submitUsername', 'submit', array('label' => 'Search username globally'))
->getForm();

$formGlobalSearch->handleRequest($request);

if ($formGlobalSearch->isValid())
    {
    // do something in the DB and refresh current page
    }

return $this->render(//all the stuff needed to render my page//);
}

Here is the relevant part of service.yml 这是service.yml的相关部分

validator.unique.UsernameExists:
    class: AppBundle\Validator\Constraints\UsernameExists
    tags:
        - { name: validator.constraint_validator, alias: UsernameExists }

Here is the validator class: 这是验证器类:

use Symfony\\Component\\Validator\\Constraint; 使用Symfony \\ Component \\ Validator \\ Constraint;

/**
 * @Annotation
 */
class UsernameExists extends Constraint
{
public $message = 'The username "%string%" does not exist.';

public function validatedBy()
{
    return 'UsernameExists';
}
}

Here is the validator: 这是验证器:

<?php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UsernameExistsValidator extends ConstraintValidator
{
public function validate($value)
    {
    $globalUserToAdd = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(
        array('username' => $value, 'enabled' => true)
        );

    if ($globalUserToAdd == null) //I did not find the user
        {
        $this->context->buildViolation($constraint->message)
            ->setParameter('%string%', $value)
            ->addViolation();
        }
    }
}

The class and the validator are in the directory "AppBundle\\Validator\\Constraints" 类和验证器在目录“ AppBundle \\ Validator \\ Constraints”中

I'm getting the following error: 我收到以下错误:

Expected argument of type "Symfony\\Component\\Validator\\ConstraintValidatorInterface", "AppBundle\\Validator\\Constraints\\UsernameExists" given 给定类型为“ Symfony \\ Component \\ Validator \\ ConstraintValidatorInterface”,“ AppBundle \\ Validator \\ Constraints \\ UsernameExists”的预期参数

I of course have the following on top of my controller: 我当然在控制器上有以下内容:

use AppBundle\Validator\Constraints\UsernameExists;

If I add the following to service.yml 如果我将以下内容添加到service.yml

arguments: ["string"]

I get the error: 我得到错误:

No default option is configured for constraint AppBundle\\Validator\\Constraints\\UsernameExists 没有为约束AppBundle \\ Validator \\ Constraints \\ UsernameExists配置默认选项

try changing: 尝试更改:

public function validatedBy()
{
    return 'UsernameExists';
}

validator.unique.UsernameExists:
    class: AppBundle\Validator\Constraints\UsernameExists

to: 至:

public function validatedBy()
{
    return 'UsernameExistsValidator';
}

validator.unique.UsernameExists:
    class: AppBundle\Validator\Constraints\UsernameExistsValidator

Merging (partially) the suggestions and debugging a bit more here is the final code. 合并(部分)建议并在此处进行更多调试是最终代码。

Validator: 验证器:

<?php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManager;

class UsernameExistsValidator extends ConstraintValidator
{

public function __construct(EntityManager $em) //added
{
    $this->em = $em;
}

public function validate($value, Constraint $constraint)
    {
    $em = $this->em;
    $globalUserToAdd = $em->getRepository('AppBundle:User')->findOneBy(
        array('username' => $value, 'enabled' => true)
        );

    if ($globalUserToAdd == null) //I did not find the user
        {
        $this->context->buildViolation($constraint->message)
            ->setParameter('%string%', $value)
            ->addViolation();
        }
    }
}

service.yml service.yml

validator.unique.UsernameExists:
    class: AppBundle\Validator\Constraints\UsernameExistsValidator
    arguments: [ @doctrine.orm.entity_manager, "string"]
    tags:
        - { name: validator.constraint_validator, alias: UsernameExists }

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

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