在symfony2.7中,我有一个包含四个数字字段的表单。提交时如何分别在以下两种情况下进行验证:
1)这四个值的总和不应超过100。 要么 2)最后三个字段值的总和应该等于第一个字段的值。
由于
答案 0 :(得分:0)
如果这是您应用程序中的一次性情况(如果我没有为此写custom constraint),您可以在处理后快速检查控制器表格和有效支票之前。
例如;
<?php
namespace Acme\Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\FormError;
class ArtistPhotoController extends Controller {
// ...
public function myFormAction(Request $request)
{
// create the form
$form = $this->createFormBuilder(null)
->add('number1', 'number', [
'required' => false,
]
)
->add('number2', 'number', [
'required' => false,
]
)
->add('number3', 'number', [
'required' => false,
]
)
->add('number4', 'number', [
'required' => false,
]
)
->add('submit', 'submit', ['label' => 'Check'])
->getForm();
$form->handleRequest($request);
// checky check for custom validation
if ($form->isSubmitted()) {
$number1 = $form->get('number1')->getData();
$number2 = $form->get('number2')->getData();
$number3 = $form->get('number3')->getData();
$number4 = $form->get('number4')->getData();
if (($number2+$number3+$number4) !== $number1) {
$form->get('number1')->addError(new FormError('Num1 not equal to 2+3+4'));
}
// any other rules you want to make up...
}
if ($form->isSubmitted() && $form->isValid()) {
// do whatever
}
return $this->render('MyBundle:foo:bar.html.twig', array(
'form' => $form->createView()
));
}
}