Symfony 2 - 表单验证 - 如果用户记录存在于数据库中

时间:2014-03-02 01:30:30

标签: php validation symfony

我与表格验证斗争..(为什么简单的事情在SF2中如此困难和复杂?:|)

我有验证器:

/Acme/Crud/Validator/Constraints/isNewsInDB.php

namespace Acme\CrudBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;


class isTitleInDB extends Constraint
{
    public $message= 'Username not unique';

    public function validatedBy()
    {
        return 'istitleindb';
              //return get_class($this).'Validator';
    }

}

/Acme/Crud/Validator/Constraints/isNewsInDBValidator.php

namespace Acme\CrudBundle\Validator\Constraints;

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

use Doctrine\Bundle\DoctrineBundle\Registry;
use Acme\CrudBundle\Entity\News;

class isTitleInDBValidator extends ConstraintValidator
{

    private $em;
    private $security_context;

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


    public function validate($value, Constraint $constraint)
    {
        $news = new News();
        $repository = $this->em->getRepository('CrudBundle:News');
        $newsitem = $repository->findOneBy(array('title' => $value));

        if (!$newsitem)
        {
            $this->context->addViolation(
                $constraint->message, 
                array('%string%' => $value)
            );
        }
    }

}

/Acme/CrudBundle/congif/services.yml:

parameters:
    validator.istitleindb.class: Acme\CrudBundle\Validator\Constraints\isTitleInDBValidator

services:
    validator.istitleindb:
        class: %validator.istitleindb.class%
        arguments: ["@doctrine"]
        tags:
            - { name: validator.constraint_validator, alias: istitleindb }

的Acme / CrudBundle /控制器/ DefaultController.php

namespace Acme\CrudBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\CrudBundle\Entity\News;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\True;
use Acme\CrudBundle\Validator\Constraints\NoWord;       // This is My test Validator
use Acme\CrudBundle\Validator\Constraints\isTitleInDB;  // My Validator as Service to check in Database

use Symfony\Component\HttpFoundation\Session\Session;


class DefaultController extends Controller
{

      private function generateAddForm($entityObject)
      {
         return $this->createFormBuilder($entityObject)
                     ->add('title', 'text', array(
                           'constraints' => array(
                              new Length(array('min' => 10, 'max' => 15)),
                              new Email(),
                              new NoWord(),
                              new isTitleInDB(),  // <------- MY DB VALIDATOR
                           )
                      ))
                     ->add('body', 'textarea')
                     ->add('save', 'submit')
                     ->getForm();
      }
      ......
}

在webBrowser中,我看到错误:

ClassNotFoundException: Attempted to load class "isTitleInDBValidator" from namespace "Acme\CrudBundle\Validator\Constraints" in /var/www/symfony2/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Validator/ConstraintValidatorFactory.php line 71. Do you need to "use" it from another namespace?

是否有更简单的方法来创建用于检查数据库中某些内容的验证器?

由于

1 个答案:

答案 0 :(得分:1)

当您注入@doctrine时,您将在构造函数中获得Doctrine \ Bundle \ DoctrineBundle \ Registry。您在服务isTitleInDBValidator中键入提示的doctrine注册表作为EntityManager。在验证功能中,您没有使用$ news变量。和 $这个 - &GT; EM-&GT; getRepository( 'CrudBundle:新闻'); 是的,你必须得到经理

$this->em->getManager()->getRepository('CrudBundle:News');