symfony验证约束ClassNotFoundException

时间:2015-09-01 13:51:17

标签: php forms validation symfony

找不到我的自定义约束类,我不知道问题出在哪里 这是错误

  

尝试从命名空间加载类“CompanyTransferConstraint”   “FM \ FMBundle \验证\约束”。你忘记了“使用”声明吗?   另一个命名空间? 500内部服务器错误 -   ClassNotFoundException的

约束类和验证器类都位于 src / FM \ FMBundle \ Validator \ Constraints

这是我的代码:
CompanyTransferConstraint

<?php

namespace FM\FMBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */

class CompanyTransferConstraint extends Constraint
{
    public $message = 'You do not have the requested amount';
    public function validatedBy()
    {
        return get_class($this).'Validator';
    }
}

CompanyTransferConstraintValidator

<?php
namespace FM\FMBundle\Validator\Constraints;

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

class CompanyTransferConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
        {

            if ($value>200) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
}

表格类型

<?php

namespace FM\FmBundle\Form\Type\Dash;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use FM\FMBundle\Validator\Constraints\CompanyTransferConstraint;
use Symfony\Component\Validator\Constraints\Type;

class CompanyTransferType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('totalAmount','integer',
                    array(
                        'constraints' => 
                            array(
                                new NotBlank(),
                                new Type('integer'),
                                new CompanyTransferConstraint(),
                            )
                    )

            )
            ->add('save','submit')
        ;
    }
    public function getName()
    {
        return 'fm_fmbundle_company_transfer';
    }
}

我还使用像这样的用户实体测试了它

/*
...
*/
use FM\FMBundle\Validator\Constraints as FmAssert;
class User extends BaseUser 
{
  /*
     .....
  */
    /**
     * @FmAssert\CompanyTransferConstraint
     */
    protected $phone;

  /*
     .....
  */
}

我收到此错误

  

AnnotationException.php第54行中的AnnotationException:[语义   错误]注释   “@FM \ FMBundle \ Validator \ Constraints \ CompanyTransferConstraint”in   属性FM \ FmBundle \ Entity \ User :: $ phone不存在,或者不能存在   自动加载。

1 个答案:

答案 0 :(得分:0)

您需要确保命名空间的大小写是一致的。

您的CompanyTransferConstraint和CompanyTransferConstraintValidator使用:

namespace FM\FmBundle\Form\Type\Dash;

您的表单类型使用:

namespace FM\FMBundle\Validator\Constraints;

FMBundle中的大写差异似乎导致了问题。您编辑的其他错误似乎也遇到了同样的问题。