[英]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.