Symfony2: How to validate an input field is not-bl

2019-02-05 09:01发布

问题:

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

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.

Any advise would be much appreciated.

UPDATE / SOLUTION - based on GeLo's remark:

<?php

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

namespace ZeroSpace\InvoicingBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="customers")
 * @UniqueEntity("billing_id")
 * @UniqueEntity("billing_name")
*/

class Customer {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer", length=6, unique=true)
     * @Assert\Length(min="6", max="6")
     */
    protected $billing_id;

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

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

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

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

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

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

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

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\Email()
     */
    protected $billing_email;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $billing_debit=false;

    /**
     * @ORM\Column(type="string", nullable=true, length=100)
     * @Assert\NotBlank(groups={"iban_required"})
     * @Assert\Iban(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 ZeroSpace\InvoicingBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;

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' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
            '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 ZeroSpace\InvoicingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;

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

}

?>

回答1:

I think this is the solution:

<?php

namespace ZeroSpace\InvoicingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use ZeroSpace\InvoicingBundle\Entity\Customer;
use ZeroSpace\InvoicingBundle\Form\CustomerType;

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 ZeroSpace\InvoicingBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\AbstractType;

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' => 'ZeroSpace\InvoicingBundle\Entity\Customer',
            '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 ZeroSpace\InvoicingBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    use Symfony\Component\Validator\Constraints as Assert;

    /**
     * @ORM\Entity
     * @ORM\Table(name="customers")
     * @UniqueEntity("billing_id")
     * @UniqueEntity("billing_name")
    */

    class Customer {

        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;

        /**
         * @ORM\Column(type="integer", length=6, unique=true)
         * @Assert\Length(min="6", max="6")
         */
        protected $billing_id;

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

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

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

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

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

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

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

        /**
         * @ORM\Column(type="string", length=100)
         * @Assert\Email()
         */
        protected $billing_email;

        /**
         * @ORM\Column(type="boolean")
         */
        protected $billing_debit=false;

        /**
         * @ORM\Column(type="string", nullable=true, length=100)
         * @Assert\NotBlank(groups={"iban_required"})
         * @Assert\Iban(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;
    }

}


回答2:

An efficient approach can be to use the validation group which can be determined on the fly. Then, given the checkbox is not checked, you use the Default validation group whereas if the checkbox is checked, you use the Default group and a custom group which will check if your field is not empty.

See this part of the documentation for more details: http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data



回答3:

could you do something like this ?

/**
 * @Assert\True()
 */
public function customValidate()
{
    return (!$this->checkboxField) or (strlen($this->inputField) > 0);
}