Symfony2 form where the data objects doesn't match exactly what needs to be filled in

前端 未结 2 1968
误落风尘
误落风尘 2021-01-07 00:12

We have a monitoring service where our monitor units keep an eye on certain machines.

I\'m creating a form to register a new machine in Symfony2.

So we have

2条回答
  •  渐次进展
    2021-01-07 00:41

    First, you should be using relationship - i.e. Machine has one monitory. I think people have problems with this because when you're used to thinking about things in terms of "id"s and foreign keys, thinking about relationships in a fully object-oriented way is new :).

    So, assuming your Machine is related to Monitor, you can now create a MachineType that embeds a MonitorType (which would be a form with the serialnumber field in it). Then, your constraints for serialnumber on your Monitor class would be used when the compound form is submitted.

    By default, when you bind all of this, it'll create a new Machine object, with a new Monitor object available via $machine->getMonitor(). If you persist, this will be two inserts. However, I'm guessing that you'd rather lookup the monitor by its serialnumber and use that existing monitor, right? To do so is easy, just short-circuit things after you bind your form.

    $form = new MachineType();
    $form->bindRequest($request);
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $machine = $form->getData();
        $serialNumber = $machine->getMonitor->getSerialNumber();
    
        $existingMonitor = $em
            ->getRepository('YourBundle:Monitor')
            ->findOneBy(array('serialNumber' => $serialNumber));
        if ($existingMonitory) {
            $machine->setMonitor($existingMonitor);
        }
    
        $em->persist($machine);
        $em->persist($machine->getMonitor());
        $em->flush();
    
        // ...
    }
    

    So, that's the idea. Biggest thing is that by not using relationships, you're putting yourself at a disadvantage. You see, by embedding these two forms together, you really do have natural access to the serialnumber field.

    Good luck!

提交回复
热议问题