在我的ZF2应用程序中,我有两个Doctrine2实体:Product
和Partner
因为在某些情况下,产品不需要合作伙伴,所以在product和partner之间存在可以为null的ManyToOne关系。
如果在表单(下拉列表)中提供了合作伙伴,它就会起作用。但如果没有,我有这个错误:
An exception occurred while executing 'SELECT t0.id AS id1, t0.title AS title2 FROM partners t0 WHERE t0.id = ?' with params [""]:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: ""`
实体:
/**
* @ORM'Entity
* @ORM'Table(name="products")
*/
class Product extends AbstractEntity
{
/* ... */
/**
* @ORM'ManyToOne(targetEntity="Partner", inversedBy="products", cascade={"persist", "merge"})
* @ORM'JoinColumn(name="partner_id", referencedColumnName="id", nullable=true)
*/
protected $partner;
/* ... */
/**
* @return Partner
*/
public function getPartner()
{
return $this->partner;
}
/**
* @param Partner $partner
*
* @return $this
*/
public function setPartner(Partner $partner)
{
$this->partner = $partner;
return $this;
}
/* ... */
}
/**
* @ORM'Entity
* @ORM'Table(name="partners")
*/
class Partner extends AbstractEntity
{
/* ... */
/**
* @ORM'OneToMany(targetEntity="Product", mappedBy="partner", cascade={"persist", "merge", "remove"})
**/
protected $products;
/* ... */
public function __construct()
{
$this->products = new ArrayCollection();
}
/* ... */
/**
* @param Product $product
*
* @return $this
*/
public function addProduct(Product $product)
{
$this->products[] = $product;
$product->setPartner($this);
return $this;
}
/**
* @param $products
*
* @return $this
*/
public function addProducts($products)
{
foreach ($products as $product)
{
$this->addProduct($product);
}
return $this;
}
/**
* @param null $products
*
* @return $this
*/
public function removeProducts($products = null)
{
if (!$products)
{
$products = $this->getProducts();
}
foreach ($products as $product)
{
if (is_object($product))
{
$this->products->removeElement($product);
}
else $this->products->remove($product);
}
return $this;
}
/**
* @return mixed
*/
public function getProducts()
{
return $this->products;
}
/**
* @param mixed $products
*
* @return $this
*/
public function setProducts($products)
{
$this->products = $products;
return $this;
}
/* ... */
}
任何帮助都将不胜感激。
感谢@hkulekci的回答。
我刚刚更新了我的输入过滤器:
public function getInputFilterSpecification()
{
return [
'partner' => ['required' => true],
/* ... */
];
}
对此:
public function getInputFilterSpecification()
{
return [
'partner' => [
'required' => true,
'continue_if_empty' => true,
'filters' => [
['name' => 'Null']
]
],
/* ... */
];
}
您需要允许将null
值传递给setPartner
方法
public function setPartner(Partner $partner = null)
{
$this->partner = $partner;
return $this;
}
此外,根据您的表单hydrator,您需要确保如果没有选择合作伙伴,则空值应转换为null
。