I have a Doctrine Entity Product with a nullable relationship to Supplier.
The FieldSets are nested. If I leave the field for Supplier empty the Doctrine Hydrator returns: A new entity was found through the relationship.
Product:
/**
* @var \Entities\Supplier
*
* @ORM\ManyToOne(targetEntity="Entities\Supplier")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="supplier_id", referencedColumnName="id", nullable=true)
* })
*/
private $supplier;
FieldSet:
/**
* Constructor for Cms\Form\SupplierFieldSet.
*
* @param ObjectManager $objectManager
*/
public function __construct(ObjectManager $objectManager)
{
parent::__construct('supplier');
$this->setObjectManager($objectManager);
$this->setHydrator(new DoctrineEntity($this->getObjectManager()))->setObject(new Supplier());
$this->addElements();
}
View:
<?php
$form->setAttribute('action', $this->url('product', array('action' => 'add')));
$form->setAttribute('class', 'form-horizontal');
$form->prepare();
echo $this->form()->openTag($form);
$product = $form->get('product');
$supplier = $product->get('supplier');
?>
<div class="form-group <?= ($this->formElementErrors($supplier->get('name'))) ? 'has-error' : ''; ?>">
<?php echo $this->formHidden($supplier->get('id')); ?>
<?php
echo $this->formRow($supplier->get('name')) . PHP_EOL;
?>
</div>
I don't want the Hydrator to try and persist a Supplier if no value has been given. The database doesn't require for the related entity to be available.
What can be done?
You say you pass an empty value, but in your SupplierFieldSet
constructor you pass a new Supplier()
. A new entity is not the same as an empty value...
When you create a new instance of supplier doctrine's unit of work sees this new entity, but since the association is not set to cascade persist it trows an exception.
You can either decide not to pass a new Supplier()
or you can add cascade={"persist"}
to your relation ship to make this work like this:
/**
* @var \Entities\Supplier
*
* @ORM\ManyToOne(targetEntity="Entities\Supplier", cascade={"persist"})
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="supplier_id", referencedColumnName="id", nullable=true)
* })
*/
private $supplier;