Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Field type hidden in Symfony2

Tags:

symfony

I want to make a hidden value for my Foreign Key Entity in controller.

My previous controller is like this (works fine):

->add('id_grup', 'entity', array('class' => 'Sifo\AdminBundle\Entity\MstGrup'))

I want to assign a hidden value to my form like this:

->add('id_grup', 'hidden', array('data' => $id))

But it gives me an error:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to Sifo\AdminBundle\Entity\DftGrupMapel::setIdGrup() must be an instance of Sifo\AdminBundle\Entity\MstGrup, string given, called in C:\Sifony\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php on line 360 and defined in C:\Sifony\src\Sifo\AdminBundle\Entity\DftGrupMapel.php line 179

How can I assign a value to a foreign key entity which is hidden?

like image 555
Jun Rikson Avatar asked Nov 11 '22 08:11

Jun Rikson


1 Answers

Finally it works! I need define the entity default before create form and don't add again in FormBuilder:

public function manageAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SifoAdminBundle:MstGrup')->find($id);

if (!$entity) {
    throw $this->createNotFoundException('Unable to find MstGrup entity.');
}  

$entity_new = new DftGrupMapel();
$entity_new->setIdGrup($entity);
$new_form    = $this->createFormBuilder($entity_new)
    ->setAction($this->generateUrl('admin_grup_mapel_manage', array('id' => $id)))
    ->setMethod('POST')
->getForm();

$new_form->handleRequest($request);

if ($new_form->isValid()) {
    $em_new = $this->getDoctrine()->getManager();
    $em_new->persist($entity_new);
    $em_new->flush();

    return $this->redirect($this->generateUrl('admin_grup_mapel_manage', array('id' => $id)));
}

return $this->render('SifoAdminBundle:DftGrupMapel:manage.html.twig', array(
    'entity'      => $entity, 
    'new_form'   => $new_form->createView(),            
));
}
like image 99
Jun Rikson Avatar answered Nov 15 '22 10:11

Jun Rikson