Php 添加约束以比较提交表单中的两个输入
提交了一份带有开始日期和结束日期的表格,我需要一份表格来检查结束日期是否晚于开始日期 问题是我不能攻击表单本身的约束,只能攻击字段,因此我只能获取字段值,而不能从其他表单输入中获取值 下面是尝试使用回调约束的代码Php 添加约束以比较提交表单中的两个输入,php,symfony-3.2,Php,Symfony 3.2,提交了一份带有开始日期和结束日期的表格,我需要一份表格来检查结束日期是否晚于开始日期 问题是我不能攻击表单本身的约束,只能攻击字段,因此我只能获取字段值,而不能从其他表单输入中获取值 下面是尝试使用回调约束的代码 class MyCustomType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) {
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
}
}