Symfony2多项选择无法验证 [英] Symfony2 multiple choice is not validating

查看:129
本文介绍了Symfony2多项选择无法验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个分配有用户和产品的购物车简单列表。
我的新表格是这样的:

$ p $ public function buildForm(FormBuilderInterface $ builder,array $ options)
$ {
$ builder-> add('cartName','text',array('label'=>'Nazwa koszyka:'))
- > add('user' ,'new'UserForm(),array('data_class'=>'Zadanie \ Bundle \Entity \User','label'=> false))
- > add('products','实体',array('label'=>'Wybierz produkty:','class'=>'Zadanie \ Bundle \Entity\Product','multiple'=> true,'required'=> true))
- > add('Zapisz','submit');
}

一切都很好,除非我可以提交表格,即使没有选择任何产品。

到目前为止,我只是通过jquery添加了required,但我不喜欢这样。有人可以向我解释为什么它不能正常工作吗? :P



编辑:
以下是控制器的代码:

  / ** 
* @Route(/ cart / edit / {id},name =_ edit_cart)
* @Template()
* /
public function editAction($ id,Request $ request)
{
$ cart = $ this-> getDoctrine() - > getRepository('ZadanieBundle:Cart') - >找到($ ID);

if($ cart == null)
{
throw $ this-> createNotFoundException('Nie znaleziono rekordu');
}

$ form = $ this-> createForm(new CartForm(),$ cart);

$ form-> handleRequest($ request);

if($ form-> isValid())
{
$ em = $ this-> getDoctrine() - > getManager();
$ data = $ form-> getData();
$ em-> persist($ data);
$ em-> flush();

$ this-> get('session') - > getFlashBag() - > set('message','Koszyk zaktualizowano。');
return $ this-> redirect($ this-> generateUrl('_ main_carts'));


$ b return array('form'=> $ form-> createView());
}

第二次编辑:



我找到了一个解决方案,(不知道是否最好,但工作:)),所以如果有人遇到这个问题:

您必须在YourBundle / Resources / config下创建验证文件(例如 validation.yml ),其中必须提供有关属性的信息。在我的情况下是:

  Zadanie \ Bundle \Entity \Cart:
属性:
cartname:
- NotBlank:〜
用户:
- NotBlank:〜
约束:
- 回调:
方法:
- [ Zadanie \ Bundle\Form\MyValidator,isUserValid〕

然后我创建了MyValidator:

  namespace Zadanie \ Bundle \Form; 
使用Symfony \ Component \Validator\ExecutionContextInterface;
使用Zadanie \ Bundle \Entity \Cart;
$ b $ class MyValidator {

public static function isUserValid(Cart $ cart,ExecutionContextInterface $ context)
{
if(!$ cart-> getUser () - > getName())
$ context-> addViolationAt('name','Proszępodaćimię。',array(),null);
if(!$ cart-> getUser() - > getSurname())
$ context-> addViolationAt('surname','Proszępodaćnazwisko。',array(),null) ;
if(count($ cart-> getProducts())== 0)
$ context-> addViolationAt('products','Proszęwybraćprodukt。',array(),null);
}
}


解决方案

@ Mati,关于你的第一个问题,关于如何选择需要的选项,这个选项只在HTML5中设置必要的属性,所以不会做任何服务器端的事情。从文档


从HTML5开始,许多浏览器可以在客户端本地执行某些验证
约束。最常见的验证是通过在所需的
字段上呈现必需属性而激活
。对于支持HTML5的浏览器,如果用户试图提交
格式的空白字段,则会显示
本机浏览器消息。


关于您的解决方案,虽然您可能需要考虑依赖内置的验证器。我很确定产品数量限制可以使用内置的 Count Collection 约束。


I'm creating a simple list of shop carts with users and products assigned to it. My form for new cart looks like this:

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('cartName', 'text', array('label' =>'Nazwa koszyka:'))
        ->add('user', new UserForm(), array('data_class' => 'Zadanie\Bundle\Entity\User', 'label' => false))
        ->add('products','entity', array('label' => 'Wybierz produkty:', 'class' =>'Zadanie\Bundle\Entity\Product' , 'multiple' => true, 'required' => true))
        ->add('Zapisz', 'submit');
}

and everything is great except that i can submit the form even without selecting any product.

By far i just added "required" by jquery, but i don't like that. Can somebody explain to me why it is not working properly? :P

EDIT: Here is the code from controller:

/**
 * @Route("/cart/edit/{id}",name="_edit_cart")
 * @Template()
 */
public function editAction($id, Request $request)
{  
    $cart = $this->getDoctrine()->getRepository('ZadanieBundle:Cart')->find($id);

    if($cart == null)
    {
        throw $this->createNotFoundException('Nie znaleziono rekordu');
    }

    $form = $this->createForm(new CartForm(), $cart);

    $form->handleRequest($request);

    if($form->isValid())
    {
        $em = $this->getDoctrine()->getManager();   
        $data = $form->getData();
        $em->persist($data);
        $em->flush();

        $this->get('session')->getFlashBag()->set('message', 'Koszyk zaktualizowano.');
        return $this->redirect($this->generateUrl('_main_carts'));

    }

    return array('form' => $form->createView());
}

SECOND EDIT:

i found a SOLUTION, ( don't know if the best, but works :) ) so if anybody encounters that:

You have to create your validation file ( validation.yml for example) under YourBundle/Resources/config, in which you have to put information about properties. In my case it was:

Zadanie\Bundle\Entity\Cart:
properties:
    cartname:
        - NotBlank: ~
    user:
          - NotBlank: ~
constraints:
    - Callback:
        methods:
            -    [Zadanie\Bundle\Form\MyValidator, isUserValid]

and then i created MyValidator:

namespace Zadanie\Bundle\Form;
use Symfony\Component\Validator\ExecutionContextInterface;
use Zadanie\Bundle\Entity\Cart;

class MyValidator {

  public static function isUserValid(Cart $cart, ExecutionContextInterface $context)
  {
    if(!$cart->getUser()->getName())
        $context->addViolationAt('name', 'Proszę podać imię.', array(), null);
    if(!$cart->getUser()->getSurname())
        $context->addViolationAt('surname', 'Proszę podać nazwisko.', array(), null);
    if(count($cart->getProducts()) == 0)
        $context->addViolationAt('products', 'Proszę wybrać produkt.', array(), null);
 }
}

解决方案

@Mati, regarding your first question about how the required option works, this option only sets the required attribute in HTML5 so does not do anything server side. From the documentation

As of HTML5, many browsers can natively enforce certain validation constraints on the client side. The most common validation is activated by rendering a required attribute on fields that are required. For browsers that support HTML5, this will result in a native browser message being displayed if the user tries to submit the form with that field blank.

Regarding your solution, that will certainly work though you may want to consider relying on the built-in validators. I'm fairly sure the product count constraint can use the built-in Count Collection constraint.

这篇关于Symfony2多项选择无法验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆