LargeTuna
LargeTuna

Reputation: 2824

Cannot set a NULL value in Symfony on a manyToOne association

I am using Symfony2. I am trying to set a NULL value on a ManyToOne association and I keep getting this error:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to WIC\SettlementBundle\Entity\SettlementReport::setSupplierPayment() must be an instance of WIC\SupplierBundle\Entity\SupplierPayment, null given, called in /Applications/MAMP/htdocs/ffss/src/WIC/SupplierBundle/Controller/SupplierPaymentController.php on line 312 and defined in /Applications/MAMP/htdocs/ffss/src/WIC/SettlementBundle/Entity/SettlementReport.php line 342

Here is the association in my settlementReport entity:

 /**
 * @ORM\ManyToOne(targetEntity="WIC\SupplierBundle\Entity\SupplierPayment", inversedBy="supplierReport")
 * @ORM\JoinColumn(name="supplierPayment_id", referencedColumnName="id", nullable=true)
 */
protected $supplierPayment;

Here is the getter and setter methods:

 /**
 * Set supplierPayment
 *
 * @param \WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment
 * @return SettlementReport
 */
public function setSupplierPayment(\WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment)
{
    $this->supplierPayment = $supplierPayment;

    return $this;
}
/**
 * Get supplierPayment
 *
 * @return \WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment
 */
public function getSupplierPayment()
{
    return $this->supplierPayment;
}

Here is my controller where I am trying to set a NULL value:

 $settlementReport = $em->getRepository('WICSettlementBundle:SettlementReport')->find($srId);
 $settlementReport->setSupplierPayment(NULL);
 $em->flush($settlementReport);

Why is it giving me that error and how can I set the value to NULL?

Thanks

Upvotes: 2

Views: 2100

Answers (1)

lxg
lxg

Reputation: 13107

If you really want to allow NULL to be set (which is apparently the case), simply change the signature as follows:

public function setSupplierPayment
    (\WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment = null)

Background: PHP forces you to pass an object of the type-casted class, and nothing else; the only exception is the null value, if the default parameter value is null, too.

Upvotes: 6

Related Questions