2017-09-14 97 views
7

我在用户使用表单创建“comision”的捆绑工作,并且我试图检查用户是否还有“信用”。所以我创建了一个自定义验证器,用于查询过去的评论,并在信用不足时抛出错误。Symfony验证

我的问题是,如果用户在“日期”字段中提交错误格式的日期(即32-13-20122 24:05)Symfony仍会尝试运行我的自定义验证,并且我得到各种错误(因为$comision->getDate()null而不是有效的DateTime对象)。

我得到这个错误:

clone method called on non-object

我也可以检查的$comision->getDate()值在我的自定义验证有效的datetime,但在我看来,它应该是没有必要的,因为我加入这个日期属性中的规则。

这是我的实体(简化)

/** 
* @MyValidation\TotalHours() 
*/ 
class Comision 
{ 

/** 
* @ORM\Column(type="datetime") 
* @Assert\DateTime() 
* @Assert\NotNull() 
*/ 
protected $date; 


/** 
* @ORM\Column(type="decimal", nullable=false, scale=1) 
* @Assert\NotBlank() 
*/ 
protected $hours; 

... 

我的窗体类...

class NewComisionType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
      $builder 
       ->add('date', DateTimeType::class, array(
       'widget' => 'single_text', 
       'label' => 'Starting date and time', 
       'format' => 'dd/MM/yyyy HH:mm' 
       )) 
       ->add('hours', ChoiceType::class, array(
        'label'=> 'How many hours', 
        'choices' => array(
         '1:00' => 1, 
         '1:30' => 1.5, 
         '2:00' => 2, 
         '2:30' => 2.5, 
         '3:00' => 3 
        ) 
       )) 
... 

而我对自定义的验证,检查过去comisions找到,如果用户仍“信用”

public function validate($comision, Constraint $constraint) 
{ 
$from = clone $comision->getDate(); 
$from->modify('first day of this month'); 

$to = clone $comision->getDate(); 
$to->modify('last day of this month'); 

$credit = $this->em->getRepository("ComisionsBundle:Comision")->comisionsByDate($comision,$from, $to); 

... 
+0

为什么不添加日期验证? https://symfony.com/doc/current/reference/constraints/Date.html或者,也许在你的自定义验证器 – kunicmarko20

+0

我做了(我编辑我的问题添加它),但它没有效果。它似乎运行所有验证规则,即使数据转换后没有有效的日期时间。 –

回答

4

一种方法是按照docs中所述对约束进行分组。

这样,您可以定义两组限制条件,而只有第一组中的所有限制条件都有效时,第二组才会生效。

关于您的用例,您可以将您的自定义约束放在与默认约束不同的组中,以确保您具有正确的$ comision DateTime对象。

+0

比我的更好的解决方案不知道这一点。谢谢! – kunicmarko20

2

To do this, you can use the GroupSequence feature. In this case, an object defines a group sequence, which determines the order groups should be validated.

https://symfony.com/doc/current/validation/sequence_provider.html

该解决方案应该是这样的:

/** 
* @MyValidation\TotalHours(groups={"Strict"}) 
* @Assert\GroupSequence({"Comision", "Strict"}) 
*/ 
class Comision 

以这种方式,将第一验证所有约束的群组中Comision(其是相同Default组)。只有该组中的所有约束都有效,第二组Strict才会被验证,确保$comision->getDate()将具有DateTime实例。

+0

这个答案与我的不同之处是什么? – Greg

+0

我很抱歉,在提交我之前没有阅读过您的答案。 – yceruto