我是Symfony2的新手。我创建了一个表单,其中包含 3 组单选按钮和一个提交按钮。为了显示表单,我使用了 FormType。现在,我必须应用一个条件,即用户最多只能选择任何 2 组单选按钮(以及最少 0 组单选按钮),而不能选择 3 组单选按钮。如果用户选择 3 组单选按钮并单击提交,那么我想向用户抛出一条错误消息,说"您只能选择 2 个"。
这是表单类型"订阅类型.php"
<?php
namespace InstituteEvents'StudentBundle'Form'Type;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
class SubscriptionsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('event1', 'choice', array('choices' => array('1' => 'Tourism', '2' => 'Food party', '3' => 'South korean food', '4' => 'Cooking', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('event2', 'choice', array('choices' => array('6' => 'Cricket', '7' => 'Football', '8' => 'Hockey', '9' => 'Baseball', '10' => 'Polo', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('event3', 'choice', array('choices' => array('11' => 'Game 1', '12' => 'Game 2', '13' => 'Game 3', '14' => 'Game 4', '15' => 'Game 5', '5' => 'None of the above'), 'data' => '5', 'expanded' => true, 'multiple' => false))
->add('register', 'submit');
}
public function getName()
{
return 'subscriptions';
}
}
这是控制器"默认控制器"
<?php
namespace InstituteProjectEvents'StudentBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use InstituteProjectEvents'StudentBundle'Entity'Subscriptions;
use InstituteProjectEvents'StudentBundle'Form'Type'SubscriptionsType;
use Symfony'Component'HttpFoundation'Request;
class DefaultController extends Controller {
public function eventsoneAction(Request $request) {
$subscriptions = new Subscriptions();
//Get the logged in users id
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
//Check if events already selected by user
$repository = $this->getDoctrine()->getManager()
->getRepository('InstituteProjectEventsStudentBundle:Subscriptions');
$query = $repository->findOneBy(array('id' => $userId));
if(($query == NULL)) {
$subscriptions->setEvent1(5);
$subscriptions->setEvent2(5);
$subscriptions->setEvent3(5);
$subscriptions->setStudents($userId);
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
$form->handleRequest($request);
}
else {
$subscriptions->setEvent1($query->getEvent1());
$subscriptions->setEvent2($query->getEvent2());
$subscriptions->setEvent3($query->getEvent3());
$subscriptions->setStudents($userId);
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
$form->handleRequest($request);
}
if ($form->isValid()) {
//Save to the Database
$em = $this->getDoctrine()->getManager();
$em->persist($subscriptions);
$em->flush();
return $this->redirect($this->generateUrl('InstituteProject_events_student_eventsregistered'));
}
if($current_date > date_format($date,"Y/m/d h:i:s a")) {
return $this->render('InstituteProjectEventsStudentBundle:Default:registrationsclosed.html.twig');
}
else {
$form = $this->createForm(new SubscriptionsType(), $subscriptions);
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsday1.html.twig', array('form' => $form ->createView()));
}
}
/**
* This action displays the Confirmation page on success.
*/
public function eventsregisteredAction() {
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsregistered.html.twig');
}
}
需要在"DefaultController.php"中编写什么验证才能应用最多选择 2 组单选按钮和最少 0 组单选按钮的规则?
将
Callback
约束应用于整个表单字段怎么样?
...
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults(array(
...
'constraints' => array(
new Callback(
array('callback' => array($this, 'validateForm'))
)
)
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if (CONDITION) {
// build and add violation
}
}
或者,您可以检查Request
对象。
为了做你想做的事情,你需要设置
'required' => false
默认情况下,"事件 1"、"事件 2"和"事件 3"(因为"必需")设置为 True。 然后,您需要为表单提交添加一个 javascript(或 jquery)侦听器,并在选择了所有三个字段时插入错误消息。 但是,您会遇到无法取消选择单选按钮的问题,因为一旦选择了单选按钮,就无法取消选择它,因此一旦您为所有三个选择了某些内容,您将永远无法在不刷新页面的情况下提交表单。因此,如果您采用此路线,您可能需要进行一些工作流程更改。
或者,您可以手动检查控制器,然后通过以下方式手动添加错误
$form->get('event3')->addError('you can only select 2');
但是您需要"清除"您的订阅,否则它将重新呈现表单,并且已经填充了以前的选择,您将进入无限循环。
我得到了答案,通过替换上面的"DefaultController.php"中的以下代码:-
if ($form->isValid()) {
//Get the submitted form's data
$subscriptions2 = $form->getData();
//To check if the user has selected more than 2 events or not
if(($subscriptions2->getEvent1() != 5) && ($subscriptions2->getEvent2() != 5) && ($subscriptions2->getEvent3() != 5)) {
echo 'You can select only a maximum of 2 events';
echo '<br>';
return $this->render('InstituteProjectEventsStudentBundle:Default:eventsday1.html.twig', array('form' => $form ->createView()));
}
在这里,需要注意的是,我已经将所有"以上都不是"单选按钮作为"SubscriptionsType.php"中的值 5 和 5 作为数据库"事件"表中所有"以上都不是"的事件 ID。