【发布时间】:2015-09-01 13:51:17
【问题描述】:
没有找到我的自定义约束类,不知道问题出在哪里。
这是错误
尝试从命名空间加载类“CompanyTransferConstraint” “FM\FMBundle\Validator\Constraints”。您是否忘记了“使用”声明 对于另一个命名空间? 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" 在 属性 FM\FmBundle\Entity\User::$phone 不存在,或不能 自动加载。
【问题讨论】:
-
必须是文件名
CompanyTransferConstraint.php的拼写错误或文件权限问题,仅此而已。 -
感谢 HPierce,这就是问题所在,我需要休息一下
-
@neoman,因为它实际上解决了问题,所以我删除了评论并将其添加为答案。
标签: php forms validation symfony