Symfony条件表格验证 [英] Symfony Conditional Form Validation

查看:52
本文介绍了Symfony条件表格验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony(2.6)中的表单。用户可以选择免费的产品,该产品将发货给用户。用户必须填写一些个人详细信息及其地址(必须填写)。如果他想指定另一个收货地址,他会选中一个未映射到实体的复选框,并填写收货地址。现在,我要提交表单,并且仅在用户选中此复选框后才验证传递地址字段。

I'm working on a Form in Symfony (2.6). The user can select a free product, which will be shipped to the user. The user has to fill in some personal details and his address (obligated). If he wants to specify another delivery address, he checks a checkbox that is not mapped to an Entity, and completes the delivery address. Now, I want to submit the form, and only validate the delivery address fields if the user has checked this checkbox. How can this be done?

地址字段和传递地址字段使用映射到相同实体的相同表单类。我将YAML文件用于约束。

The address Fields and the Delivery Address Fields use the same Form Class mapped to the same Entity. I Use a YAML-file for my constraints.

(验证的一部分)。yml:

(part of) validation.yml:

AppBundle\Entity\Address:
    properties:
        street:
          - NotBlank: { message: "Please fill in your first name." }
          - Length:
              min: 3
              max: 256
              minMessage: "Please fill in your street name."
              maxMessage: "Please fill in your street name."
        number:
          - NotBlank: { message: "Please fill in your house number." }
          - Length:
              min: 1
              max: 10
              minMessage: "Please fill in your house number."
              maxMessage: "Please fill in your house number."
        postCode:
          - NotBlank: { message: "Please fill in your postal code." }
          - Length:
              min: 2
              max: 10
              minMessage: "Please fill in your postal code."
              maxMessage: "Please fill in your postal code."
        city:
          - NotBlank: { message: "Please fill in your city." }
          - Length:
              min: 2
              max: 256
              minMessage: "Please fill in your city."
              maxMessage: "Please fill in your city."
          - Type:
              type: alpha
              message: "Please fill in your city."
        country:
          - NotBlank: { message: "Please select your country." }
          - Country: ~

AppBundle\Entity\Product:
    properties:
      product:
        - NotBlank: { message: "Please select your product." }
        - Type:
            type: integer
            message: "Please select your product."
      contact:
          - Type:
              type: AppBundle\Entity\Contact
          - Valid: ~
      deliveryAddress:
          - Type:
              type: AppBundle\Entity\Address
          - Valid: ~

产品表单类别:

    <?php

class ProductFormType extends AbstractType
{

    /**
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product'
        ));
    }

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'product';
    }


    /**
     *
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('contact', new ContactFormType()); //CONTACTFORMTYPE also has an AddressFormType for the Address Fields

        $builder->add('differentDeliveryAddress', 'checkbox', array( //delivery address is only specific for this Form
            'label'     => 'Different Shipping Address',
            'required'  => false,
            'mapped'    => false
        ));
        $builder->add('deliveryAddress', new AddressFormType());

        //specific

        $builder->add('product', 'choice', array(
            'choices' => array('a'=>'product x','b' => 'product y'),
            'required' => true,
            'invalid_message' => 'This field is required',
            'label' => 'Your Free Product',
        ));

        $builder->add('submit', 'button', array('label' => 'Submit'));
    }
}

最后,在我的控制器中执行getProductFormAction

Finally the getProductFormAction in My Controller

   public function getProductFormAction(Request $request)
{

    $product = new Product();
    $form    = $this->get('form.factory')->create(new ProductFormType($product);

    $form->handleRequest($request);

    if($form->isValid()){
        return new Response('Success'); //just to test
    }

    return $this->render(
        'productForm.html.twig',
        array(
            'pageTitle'   => 'Test',
            'form'        => $form->createView()
        )
    );
}


推荐答案

这可以相对容易地通过组来实现。

This can relatively easily be achieved through groups.

首先,将组添加到您只想添加的字段中

First, add groups to the fields you only want to validate on certain occasions (your delivery address) fields.

street:
      - NotBlank: 
          message: "Please fill in your first name."
          groups: [delivery]
      - Length:
          min: 3
          max: 256
          minMessage: "Please fill in your street name."
          maxMessage: "Please fill in your street name."
          groups: [delivery]

现在,这些验证在特定的组中进行,除非明确要求这样做,否则它们将不会得到验证。

Now that these validations are in a specific group, they will not be validated unless explicitly told to do so.

现在,让我们表单确定何时验证此组。

So now, we let the form determine when to validate this group.

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function (FormInterface $form) {
            $data = $form->getData();

            if ($data->differentDeliveryAddress()) {
                return array('Default', 'delivery');
            }

            return array('Default');
        },
    ));
}

此处,表单将始终验证默认组(所有验证均不包含任何组),并且还会在设置了differentDeliveryAddress时验证送货组。

Here the form will always validate the 'Default' group (all validations without any groups set), and will also validate the 'delivery' group when differentDeliveryAddress is set.

希望这会有所帮助

这篇关于Symfony条件表格验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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