2017-05-29 58 views
0

提交了一个包含开始和结束日期的表单,我需要一个Constraint来检查结束日期是否晚于开始日期。添加约束以提交的形式比较两个输入

问题是,我不能攻击一个约束到表单本身,只能到这个字段,因此我只能得到字段值,没有来自其他表单输入的值。

这是试图使用回调约束的代码。

class MyCustomType extends AbstractType 
{ 
/** 
* {@inheritdoc} 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
    ->add('dateFrom', null, [ 
     'constraints' => [ 
      new NotBlank([ 
       'message' => 'Error' 
      ]) 
     ], 
    ]) 
    ->add('dateTo', null, [ 
     'constraints' => [ 
      new NotBlank([ 
       'message' => 'Error!' 
      ]), 
      new Callback(function($object, ExecutionContextInterface $context, $payload) { 
       // Ėobject there is the field on which i check the constraint and i have no possible way to get the dateFrom value here 
      }) 
     ], 
    ]) 

例如:

  • 开始日期2017年1月1日 结束日期2018年1月1日 的形式将是有效的。

  • 开始日期2017-01-01 结束日期2016-12-30 该表格将无效。

回答

0
$form=$builder 
    ->add('dateFrom', null, [ 
     'constraints' => [ 
      new NotBlank([ 
       'message' => 'Error' 
      ]) 
     ], 
    ]) 
    ->add('dateTo', null, [ 
     'constraints' => [ 
      new NotBlank([ 
       'message' => 'Error!' 
      ]), 
      new Callback(function($object, ExecutionContextInterface $context, $payload) { 
       // Ėobject there is the field on which i check the constraint and i have no possible way to get the dateFrom value here 
      }) 
     ], 
    ]); 

//Before submit controll date. 
$builder->addEventListener(FormEvents::PRE_SUBMIT,function (FormEvent $event) 
{ 

    //Form data 
    $data=$event->getData(); 
    if($data['dateFrom']>$data['dateTo']) 
    { 
     //valid 
    } 
    else 
    { 
     //not valid 
    } 

} 
+0

我相信这会工作,但有应与验证约束标准的解决方案。 –