how to make a property to be "merged" or initialized when deserializing with JMSSerializerBundle

Viewed 417

I'm using JMSSerializer - along with the Doctrine constructor - in order to deserialize an object sent.

My (simplified) entities are the following. I omit the code I think is useless:

Widget
{
   protected $id;

    /**
     * @ORM\OneToMany(
     *     targetEntity="Belka\Iso50k1Bundle\Entity\VarSelection",
     *     mappedBy="widget",
     *     cascade={"persist", "remove", "detach", "merge"})
     * @Serializer\Groups({"o-all-getCWidget", "i-p2-create", "o-all-getWidget", "i-p3-create", "i-p2-editWidget"})
     * @Type("ArrayCollection<Belka\Iso50k1Bundle\Entity\VarSelection>")
     */
    protected $varsSelection;
}


/**
 * @ORM\Entity()
 *
 * @ORM\InheritanceType("SINGLE_TABLE")
 *
 * @ORM\DiscriminatorColumn(
 *     name="vartype",
 *     type="string")
 *
 * @ORM\DiscriminatorMap({
 *     "PHY" = "PhyVarSelection"
 * })
 * 
 * @ORM\HasLifecycleCallbacks()
 */
abstract class VarSelection
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue("SEQUENCE")
     * @Serializer\groups({"o-all-getCWidget", "o-all-getWidget", "i-p2-editWidget"})
     */
protected $id;
}



class PhyVarSelection extends VarSelection
{
    /**
     * @var PhyVar
     *
     * @ORM\ManyToOne(
     *     targetEntity="Belka\Iso50k1Bundle\Entity\PhyVar",
     *     cascade={"persist", "merge", "detach"})
     *
     * @ORM\JoinColumn(
     *     name="phy_var_sel",
     *     referencedColumnName="id",
     *     nullable=false)
     */
    protected $phyVar;
}

class PhyVar extends Variable
{
    /**
     * @ORM\Column(type="string")
     * @ORM\Id
     *
     * @Serializer\Groups({"o-p2-getCMeters", "o-all-getWidget"})
     * @Assert\Regex("/(PHY)_\d+_\d+_\w+/")
     */
    protected $id;

    /**
     * @ORM\Column(type="text", name="varname")
     * @Serializer\Groups({"o-p2-getCMeters", "o-all-getWidget", "o-all-getCWidget"})
     */
    protected $varName;

    ...

}

I try to deserialize an object that represents a Widget entity already persisted, along with which an array of varselection with their own id specified - if already persisted - and without their own id if they are new and to be persisted.

Deserialization works:

$context = new DeserializationContext();
$context->setGroups('i-p2-editWidget');
$data = $this->serializer->deserialize($content, $FQCN, 'json', $context);

but $data has always Widget::$varsSelection[]::$phyVar as a proxy class initialized, with only the id properly set. What I have to do so as to have it all is:

foreach ($data->getVarsSelection() as $varSel) {
    $varSel->getVar();
}

why is that? How can have it initialized already? I don't want to spend time cycling and fetching data from DB again.

edit

I've added a domain of the entities so as to get the idea of what I'm deserializing Domain of the entities

1 Answers
Related