[英]Add constraint to compare two inputs in submitted form
带有开始日期和结束日期的表单已提交,我需要一个约束条件 ,该约束条件将检查结束日期是否晚于开始日期。
问题是我不能对表单本身进行约束,而只能对字段进行约束,因此我只能获取字段值,而不能从其他表单输入获取值。
这是尝试使用回调约束的代码。
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-01-01结束日期2018-01-01该表格将有效。
开始日期2017-01-01结束日期2016-12-30表格无效。
$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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.