2

我正在创建一个简单的购物车列表,其中包含分配给它的用户和产品。我的新购物车表格如下所示:

 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');
}

一切都很好,除了我可以在不选择任何产品的情况下提交表格。

到目前为止,我刚刚添加了 jquery 的“必需”,但我不喜欢这样。有人可以向我解释为什么它不能正常工作吗?:P

编辑: 这是来自控制器的代码:

/**
 * @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());
}

第二次编辑:

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

您必须在 YourBundle/Resources/config 下创建您的验证文件(例如validation.yml),您必须在其中放置有关属性的信息。就我而言,它是:

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

然后我创建了 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);
 }
}
4

1 回答 1

0

@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.

于 2013-12-29T23:04:13.640 回答