I have a MainConfig
entity that has One-to-one relationship with LedConfig
entity. LedConfig
can be null.
<?php
namespace ...
use Doctrine\ORM\Mapping as ORM;
...
/**
* @ORM\Entity
*/
class MainConfig
{
...
/**
* @ORM\OneToOne(targetEntity="...\LedConfig", cascade={"all"})
* @ORM\JoinColumn(name="led_config_id", referencedColumnName="id", nullable=true, unique = true)
*/
private $ledConfig = null;
...
}
<?php
namespace ...
use Doctrine\ORM\Mapping as ORM;
...
/**
* @ORM\Entity
*/
class LedConfig
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="float")
* @Assert\Type(type="float")
*/
private $lowerVoltageThreshold = 11.9;
/**
* @ORM\Column(type="float")
* @Assert\Type(type="float")
*/
private $upperVoltageThreshold = 12.85;
}
<?php
namespace ...;
use Symfony\Component\Form\AbstractType;
...
class MainConfigType extends AbstractType
{
...
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(...)
->add('ledConfig', LedConfigType::class)
...
}
...
}
I am inserting a main config into a database automatically without using Symfony forms. So, if I set led config to null in the code - field led_config_id
inside main config table is correctly set to NULL.
But, when I am updating the main config, I am using HTTP PUT request that is processed through Symfony forms. I am using JSON, so request body looks like this:
{..., "ssid":"test","runningMode":"force_on","led_config":null, ...}
After the form is processed, property $ledConfig
inside MainConfig entity is magically instantiated as LedConfig
object with all properties set to NULL?!
And database update fails because it tries to save LedEnttiy with empty fields.
Why does it happen?
Can someone please help me and indicate what I did wrong?
EDIT: I could hack it in the controller update action, after the form validation:
/**
* @Route("...")
* @Method("PUT")
*/
public function updateMainConfigAction($id, Request $request)
{
$requestData = \GuzzleHttp\json_decode($request->getContent(), true);
...
if (!$form->isValid()) {
throw $this->throwApiProblemValidationException($form);
}
if (empty($requestData['led_config'])) {
$mainConfig->setLedConfig(null);
}
$em = $this->getDoctrine()->getManager();
$em->persist($mainConfig);
$em->flush();
...
}
but that is kind of dirty...