1
votes

I'm creating a form for an entity (sample) that contains a known number of form of an other entity (Result).

Sample has a collection of Result. (and also a collection of Parameter)

In my controller the code look like this

$em = $this->getDoctrine()->getManager();
$sample = $em->getRepository('ReceptionBundle:Sample')->find($id);
$formBuilder = $this->createFormBuilder();

$i = 0;
foreach ($sample->getParameter() as $param){

    $fb = $this->get('form.factory')->createNamedBuilder($i, FormType::Class, $sample);
    if ($param->getCriteria()===false){
        $fb->add('result', Result1Type::class, array('data_class'=>null));
    }
    else {
        $fb->add('result', Result2Type::class, array('data_class'=>null));
    }
    $formBuilder->add($fb);
    $i++;

}
$formBuilder->add('save',      SubmitType::class);
$form = $formBuilder->getForm();

When I try with this I have an error before to see the form :

The form's view data is expected to be an instance of class ReceptionBundle\Entity\Result, but is an instance of class Doctrine\ORM\PersistentCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\ORM\PersistentCollection to an instance of ReceptionBundle\Entity\Result.

So, when I try to set the "data_class" option to null, I can display the form, but I can't submit it :

Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "ReceptionBundle\Entity\Sample#$result", got "boolean" instead.

I don't know why is receiving a boolean.

1
Finaly, I didn,t use the Result1Type::class, it was not necessary. I use the collection type, the thing is that you can create directly the new results in the controller this way - Guy1871

1 Answers

0
votes

Finaly, I didn,t use the Result1Type::class, it was not necessary. I use the collection type, the thing is that you can create directly the new results in the controller this way

foreach ($sample->getParameter() as $param){

$result = new Result();
$sample->addResult($result);
}
 $form = $this->createForm(AnalyseType::class, $sample);

The result is directly syncronised with the form.