0

I have form in Symfony2 containing 2 sub form types representing 2 relations in my entity. invoiceAddress is required always and it works OK, but i want deliveryAddress keep optional only when all inputs of deliveryAdress are empty. When i set it like not required symfony sets deliveryAddress as null when nothing is filled in form, but when some fields are filled it do not run validation of asserts on that entity. So what i am trying to achieve is tell the symfony when form is whole empty then set deliveryAddress as null but when something in form is set then run validations in normal way. Is there any way how to do it? Thanks.

My form type looks like this and in controller i have standart $form->isValid condition.

$builder->add('invoiceAddress',new AddressType())
        ->add('deliveryAddress', new AddressType(),["required" => false])

AdressType contains only some primitive type mappings like this:

$builder->add('firstName')
        ->add('lastName')...

And in Address entity:

    /**
 * @Assert\NotBlank
 * @ORM\Column
 * @var string
 */
private $firstName;

/**
 * @Assert\NotBlank
 * @ORM\Column
 * @var string
 */
private $lastName;

1 Answer 1

1

If you setup entities and assertions correctly this should work out of the box. When the Address object is empty the form component will return null as model data and set it on the parent. When a property is null the validation is skipped for that property. It should look something like this:

class Order
{
    /**
     * @var Address
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Address")
     * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
     *
     * @Assert\NotBlank()
     * @Assert\Valid()
     */
    private $invoiceAddress;

    /**
     * @var Address
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Address")
     * @ORM\JoinColumn(onDelete="SET NULL", nullable=true)
     *
     * @Assert\Valid()
     */
    private $deliveryAddress;

    public function getInvoiceAddress()
    {
        return $this->invoiceAddress;
    }

    public function setInvoiceAddress(Address $address)
    {
        $this->invoiceAddress = $address;
    }

    public function getDeliveryAddress()
    {
        return $this->deliveryAddress;
    }

    public function setDeliveryAddress(Address $address = null)
    {
        $this->deliveryAddress = $address;
    }
}
1
  • @Assert\Valid() on the deliveryAddress rocks! Thank you :)
    – Ales
    Apr 9, 2016 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.