我是Symfony2的新手。我创建了一个包含3组单选按钮和一个提交按钮的表单。为了显示表单,我使用了FormType。现在,我必须应用一个条件,即用户只能选择最多2组单选按钮(最少0组单选按钮)而不能选择3组单选按钮。如果用户选择3组单选按钮并单击提交,那么我想向用户抛出一条错误消息,说“你只能选择2”。
这是FormType“SubscriptionsType.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';
}
}
这是控制器“DefaultController”
<?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的规则?
答案 0 :(得分:2)
如何将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
对象..
答案 1 :(得分:1)
为了做你想做的事,你需要设置
'required' => false
到event1,event2和event3,因为默认情况下必需设置为true。然后,您需要为表单提交添加javascript(或jquery)侦听器,并且如果选择了所有三个字段,则插入错误消息。但是,您会遇到无法取消选择单选按钮的问题,因为一旦您选择单选按钮就无法取消选择,所以一旦您为所有这三个选择了某些内容,您就会遇到这样的问题。在没有刷新页面的情况下永远无法提交表单。因此,如果采用这种方式,您可能希望进行一些工作流程更改。
或者,您只需在控制器中进行手动检查,然后通过
手动添加错误$form->get('event3')->addError('you can only select 2');
但是你需要清除&#39;您的订阅,否则它将重新呈现已填充先前选择的表单,您将进入无限循环。
答案 2 :(得分:1)
我通过替换上面的&#34; DefaultController.php&#34;中的以下代码得到了答案。 : -
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()));
}
在这里,需要注意的是,我已经给出了以上所有&#34;以及#34;单选按钮为&#34; SubscriptionsType.php&#34;和5作为所有&#34;以上所有&#34;的事件ID在&#34;事件&#34;的表格中在数据库中。