Symfony2:如何验证输入字段不为空,仅当复选框为真时? [英] Symfony2: How to validate an input field is not-blank, only when checkbox is true?

查看:19
本文介绍了Symfony2:如何验证输入字段不为空,仅当复选框为真时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Symfony2 中,仅当复选框的值为 1(真)时,如何验证输入字段不是空白的 - 否则允许空白?

Within Symfony2 how to validate an inputfield is not-blank, only when the value of a checkbox is 1 (True) - otherwise blank is allowed?

更准确地说,我有一个带有复选框的表单和一个带有文本类型的输入字段.在 Symfony 中的实体上应该有一个检查,当复选框的值为 True (1)/选中时,输入的值不能为空.我在实体中使用注释.

To be more precise, I have a form with a checkbox and an input field with type text. On the Entity in Symfony there should be a check that when the value of the checkbox is True (1) / checked, the value of the input can't be blank. I am using annotations within the Entity.

任何建议将不胜感激.

更新/解决方案 - 基于 GeLo 的评论:

UPDATE / SOLUTION - based on GeLo's remark:

<?php

// src/ZeroSpace/Invoicing/Entity/Customer.php

namespace ZeroSpaceInvoicingBundleEntity;

use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentValidatorConstraints as Assert;

/**
 * @ORMEntity
 * @ORMTable(name="customers")
 * @UniqueEntity("billing_id")
 * @UniqueEntity("billing_name")
*/

class Customer {

    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORMColumn(type="integer", length=6, unique=true)
     * @AssertLength(min="6", max="6")
     */
    protected $billing_id;

    /**
     * @ORMColumn(type="string", length=100, unique=true)
     */
    protected $billing_name;

    /**
     * @ORMColumn(type="string", nullable=true, length=100)
     */
    protected $billing_consignee;

    /**
     * @ORMColumn(type="string", length=100)
     */
    protected $billing_street;

    /**
     * @ORMColumn(type="string", length=100)
     */
    protected $billing_address;

    /**
     * @ORMColumn(type="string", length=100)
     */
    protected $billing_zip;

    /**
     * @ORMColumn(type="string", length=100)
     */
    protected $billing_city;

    /**
     * @ORMColumn(type="string", length=100)
     */
    protected $billing_country;

    /**
     * @ORMColumn(type="string", length=100)
     * @AssertEmail()
     */
    protected $billing_email;

    /**
     * @ORMColumn(type="boolean")
     */
    protected $billing_debit=false;

    /**
     * @ORMColumn(type="string", nullable=true, length=100)
     * @AssertNotBlank(groups={"iban_required"})
     * @AssertIban(message = "This is not a valid International Bank Account Number (IBAN).")
     */
    protected $billing_iban;

    protected $locations;


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set billing_id
 *
 * @param integer $billingId
 * @return Customer
 */
public function setBillingId($billingId)
{
    $this->billing_id = $billingId;

    return $this;
}

/**
 * Get billing_id
 *
 * @return integer 
 */
public function getBillingId()
{
    return $this->billing_id;
}

/**
 * Set billing_name
 *
 * @param string $billingName
 * @return Customer
 */
public function setBillingName($billingName)
{
    $this->billing_name = $billingName;

    return $this;
}

/**
 * Get billing_name
 *
 * @return string 
 */
public function getBillingName()
{
    return $this->billing_name;
}

/**
 * Set billing_consignee
 *
 * @param string $billingConsignee
 * @return Customer
 */
public function setBillingConsignee($billingConsignee)
{
    $this->billing_consignee = $billingConsignee;

    return $this;
}

/**
 * Get billing_consignee
 *
 * @return string 
 */
public function getBillingConsignee()
{
    return $this->billing_consignee;
}

/**
 * Set billing_street
 *
 * @param string $billingStreet
 * @return Customer
 */
public function setBillingStreet($billingStreet)
{
    $this->billing_street = $billingStreet;

    return $this;
}

/**
 * Get billing_street
 *
 * @return string 
 */
public function getBillingStreet()
{
    return $this->billing_street;
}

/**
 * Set billing_address
 *
 * @param string $billingAddress
 * @return Customer
 */
public function setBillingAddress($billingAddress)
{
    $this->billing_address = $billingAddress;

    return $this;
}

/**
 * Get billing_address
 *
 * @return string 
 */
public function getBillingAddress()
{
    return $this->billing_address;
}

/**
 * Set billing_zip
 *
 * @param string $billingZip
 * @return Customer
 */
public function setBillingZip($billingZip)
{
    $this->billing_zip = $billingZip;

    return $this;
}

/**
 * Get billing_zip
 *
 * @return string 
 */
public function getBillingZip()
{
    return $this->billing_zip;
}

/**
 * Set billing_city
 *
 * @param string $billingCity
 * @return Customer
 */
public function setBillingCity($billingCity)
{
    $this->billing_city = $billingCity;

    return $this;
}

/**
 * Get billing_city
 *
 * @return string 
 */
public function getBillingCity()
{
    return $this->billing_city;
}

/**
 * Set billing_country
 *
 * @param string $billingCountry
 * @return Customer
 */
public function setBillingCountry($billingCountry)
{
    $this->billing_country = $billingCountry;

    return $this;
}

/**
 * Get billing_country
 *
 * @return string 
 */
public function getBillingCountry()
{
    return $this->billing_country;
}

/**
 * Set billing_email
 *
 * @param string $billingEmail
 * @return Customer
 */
public function setBillingEmail($billingEmail)
{
    $this->billing_email = $billingEmail;

    return $this;
}

/**
 * Get billing_email
 *
 * @return string 
 */
public function getBillingEmail()
{
    return $this->billing_email;
}

/**
 * Set billing_debit
 *
 * @param boolean $billingDebit
 * @return Customer
 */
public function setBillingDebit($billingDebit)
{
    $this->billing_debit = $billingDebit;

    return $this;
}

/**
 * Get billing_debit
 *
 * @return boolean 
 */
public function getBillingDebit()
{
    return $this->billing_debit;
}

/**
 * Set billing_iban
 *
 * @param string $billingIban
 * @return Customer
 */
public function setBillingIban($billingIban)
{
    $this->billing_iban = $billingIban;
    return $this;
}

/**
 * Get billing_iban
 *
 * @return string 
 */
public function getBillingIban() {
    return $this->billing_iban;
}

}

    <?php
// src/Blogger/BlogBundle/Form/CustomerType.php

namespace ZeroSpaceInvoicingBundleForm;

use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentFormFormInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;
use SymfonyComponentFormAbstractType;

class CustomerType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {  
        $builder->add('billing_id');
        $builder->add('billing_name');
        $builder->add('billing_consignee');
        $builder->add('billing_street');
        $builder->add('billing_address');
        $builder->add('billing_zip');
        $builder->add('billing_city');
        $builder->add('billing_country');
        $builder->add('billing_email', 'email');
        $builder->add('billing_debit', 'checkbox');
        $builder->add('billing_iban');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'ZeroSpaceInvoicingBundleEntityCustomer',
            'validation_groups' => function(FormInterface $form) {
                $data = $form->getData();
                if($data->getBillingDebit() == 1) {
                    return array('Default', 'iban_required');
                }
                else {
                    return array('Default');
                }
            },
        ));
    }

    public function getName() {
        return 'customer';
    }
}


?>


<?php

namespace ZeroSpaceInvoicingBundleController;

use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;

use ZeroSpaceInvoicingBundleEntityCustomer;
use ZeroSpaceInvoicingBundleFormCustomerType;

class CustomerController extends Controller {

    public function createAction(Request $request) {

        $form = $this->createForm(new CustomerType(), new Customer());
        $form->handleRequest($request);

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

            return $this->redirect($this->generateUrl('customer_list'));
            // return $this->redirect($this->generateUrl('task_success'));
        }

        return $this->render('InvoicingBundle:Page:customers.html.twig', array(
            'form' => $form->createView()
        ));   
    }

    public function listAction() {
        $customers = $this->getDoctrine()->getManager()
            ->createQuery('SELECT c FROM InvoicingBundle:Customer c')
            ->execute();

        return $this->render(
            'InvoicingBundle:Customer:list.html.twig', 
            array('customers' => $customers));
    }

    public function showAction($id) {
        $customer = $this->get('doctrine')
            ->getManager()
            ->getRepository('InvoicingBundle:Customer')
            ->find($id);

        if (!$post) {
            // cause the 404 page not found to be displayed
            throw $this->createNotFoundException();
        }

        return $this->render(
            'InvoicingBundle:Page:customers.html.twig',
            array('customer' => $customer)
        );
    }

}

?>

推荐答案

我认为这是解决方案:

<?php

namespace ZeroSpaceInvoicingBundleController;

use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;

use ZeroSpaceInvoicingBundleEntityCustomer;
use ZeroSpaceInvoicingBundleFormCustomerType;

class CustomerController extends Controller {

    public function createAction(Request $request) {

        $form = $this->createForm(new CustomerType(), new Customer());
        $form->handleRequest($request);

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

            return $this->redirect($this->generateUrl('customer_list'));
            // return $this->redirect($this->generateUrl('task_success'));
        }

        return $this->render('InvoicingBundle:Page:customers.html.twig', array(
            'form' => $form->createView()
        ));   
    }

    public function listAction() {
        $customers = $this->getDoctrine()->getManager()
            ->createQuery('SELECT c FROM InvoicingBundle:Customer c')
            ->execute();

        return $this->render(
            'InvoicingBundle:Customer:list.html.twig', 
            array('customers' => $customers));
    }

    public function showAction($id) {
        $customer = $this->get('doctrine')
            ->getManager()
            ->getRepository('InvoicingBundle:Customer')
            ->find($id);

        if (!$post) {
            // cause the 404 page not found to be displayed
            throw $this->createNotFoundException();
        }

        return $this->render(
            'InvoicingBundle:Page:customers.html.twig',
            array('customer' => $customer)
        );
    }

}

?>

    <?php
// src/Blogger/BlogBundle/Form/CustomerType.php

namespace ZeroSpaceInvoicingBundleForm;

use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentFormFormInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;
use SymfonyComponentFormAbstractType;

class CustomerType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {  
        $builder->add('billing_id');
        $builder->add('billing_name');
        $builder->add('billing_consignee');
        $builder->add('billing_street');
        $builder->add('billing_address');
        $builder->add('billing_zip');
        $builder->add('billing_city');
        $builder->add('billing_country');
        $builder->add('billing_email', 'email');
        $builder->add('billing_debit', 'checkbox');
        $builder->add('billing_iban');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'ZeroSpaceInvoicingBundleEntityCustomer',
            'validation_groups' => function(FormInterface $form) {
                $data = $form->getData();
                if($data->getBillingDebit() == 1) {
                    return array('Default', 'iban_required');
                }
                else {
                    return array('Default');
                }
            },
        ));
    }

    public function getName() {
        return 'customer';
    }
}


?>

    <?php

    // src/ZeroSpace/Invoicing/Entity/Customer.php

    namespace ZeroSpaceInvoicingBundleEntity;

    use DoctrineORMMapping as ORM;
    use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
    use SymfonyComponentValidatorConstraints as Assert;

    /**
     * @ORMEntity
     * @ORMTable(name="customers")
     * @UniqueEntity("billing_id")
     * @UniqueEntity("billing_name")
    */

    class Customer {

        /**
         * @ORMId
         * @ORMColumn(type="integer")
         * @ORMGeneratedValue(strategy="AUTO")
         */
        protected $id;

        /**
         * @ORMColumn(type="integer", length=6, unique=true)
         * @AssertLength(min="6", max="6")
         */
        protected $billing_id;

        /**
         * @ORMColumn(type="string", length=100, unique=true)
         */
        protected $billing_name;

        /**
         * @ORMColumn(type="string", nullable=true, length=100)
         */
        protected $billing_consignee;

        /**
         * @ORMColumn(type="string", length=100)
         */
        protected $billing_street;

        /**
         * @ORMColumn(type="string", length=100)
         */
        protected $billing_address;

        /**
         * @ORMColumn(type="string", length=100)
         */
        protected $billing_zip;

        /**
         * @ORMColumn(type="string", length=100)
         */
        protected $billing_city;

        /**
         * @ORMColumn(type="string", length=100)
         */
        protected $billing_country;

        /**
         * @ORMColumn(type="string", length=100)
         * @AssertEmail()
         */
        protected $billing_email;

        /**
         * @ORMColumn(type="boolean")
         */
        protected $billing_debit=false;

        /**
         * @ORMColumn(type="string", nullable=true, length=100)
         * @AssertNotBlank(groups={"iban_required"})
         * @AssertIban(message = "This is not a valid International Bank Account Number (IBAN).")
         */
        protected $billing_iban;

        protected $locations;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set billing_id
     *
     * @param integer $billingId
     * @return Customer
     */
    public function setBillingId($billingId)
    {
        $this->billing_id = $billingId;

        return $this;
    }

    /**
     * Get billing_id
     *
     * @return integer 
     */
    public function getBillingId()
    {
        return $this->billing_id;
    }

    /**
     * Set billing_name
     *
     * @param string $billingName
     * @return Customer
     */
    public function setBillingName($billingName)
    {
        $this->billing_name = $billingName;

        return $this;
    }

    /**
     * Get billing_name
     *
     * @return string 
     */
    public function getBillingName()
    {
        return $this->billing_name;
    }

    /**
     * Set billing_consignee
     *
     * @param string $billingConsignee
     * @return Customer
     */
    public function setBillingConsignee($billingConsignee)
    {
        $this->billing_consignee = $billingConsignee;

        return $this;
    }

    /**
     * Get billing_consignee
     *
     * @return string 
     */
    public function getBillingConsignee()
    {
        return $this->billing_consignee;
    }

    /**
     * Set billing_street
     *
     * @param string $billingStreet
     * @return Customer
     */
    public function setBillingStreet($billingStreet)
    {
        $this->billing_street = $billingStreet;

        return $this;
    }

    /**
     * Get billing_street
     *
     * @return string 
     */
    public function getBillingStreet()
    {
        return $this->billing_street;
    }

    /**
     * Set billing_address
     *
     * @param string $billingAddress
     * @return Customer
     */
    public function setBillingAddress($billingAddress)
    {
        $this->billing_address = $billingAddress;

        return $this;
    }

    /**
     * Get billing_address
     *
     * @return string 
     */
    public function getBillingAddress()
    {
        return $this->billing_address;
    }

    /**
     * Set billing_zip
     *
     * @param string $billingZip
     * @return Customer
     */
    public function setBillingZip($billingZip)
    {
        $this->billing_zip = $billingZip;

        return $this;
    }

    /**
     * Get billing_zip
     *
     * @return string 
     */
    public function getBillingZip()
    {
        return $this->billing_zip;
    }

    /**
     * Set billing_city
     *
     * @param string $billingCity
     * @return Customer
     */
    public function setBillingCity($billingCity)
    {
        $this->billing_city = $billingCity;

        return $this;
    }

    /**
     * Get billing_city
     *
     * @return string 
     */
    public function getBillingCity()
    {
        return $this->billing_city;
    }

    /**
     * Set billing_country
     *
     * @param string $billingCountry
     * @return Customer
     */
    public function setBillingCountry($billingCountry)
    {
        $this->billing_country = $billingCountry;

        return $this;
    }

    /**
     * Get billing_country
     *
     * @return string 
     */
    public function getBillingCountry()
    {
        return $this->billing_country;
    }

    /**
     * Set billing_email
     *
     * @param string $billingEmail
     * @return Customer
     */
    public function setBillingEmail($billingEmail)
    {
        $this->billing_email = $billingEmail;

        return $this;
    }

    /**
     * Get billing_email
     *
     * @return string 
     */
    public function getBillingEmail()
    {
        return $this->billing_email;
    }

    /**
     * Set billing_debit
     *
     * @param boolean $billingDebit
     * @return Customer
     */
    public function setBillingDebit($billingDebit)
    {
        $this->billing_debit = $billingDebit;

        return $this;
    }

    /**
     * Get billing_debit
     *
     * @return boolean 
     */
    public function getBillingDebit()
    {
        return $this->billing_debit;
    }

    /**
     * Set billing_iban
     *
     * @param string $billingIban
     * @return Customer
     */
    public function setBillingIban($billingIban)
    {
        $this->billing_iban = $billingIban;
        return $this;
    }

    /**
     * Get billing_iban
     *
     * @return string 
     */
    public function getBillingIban() {
        return $this->billing_iban;
    }

}

这篇关于Symfony2:如何验证输入字段不为空,仅当复选框为真时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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