I have two entities Project and Task. Task`s project_id value is mapped with project`s id.Every time creating a new task for a specific project, the project_id in the Task table should be set. Is there another way of doing this except using the hidden input field form?
createAction of TaskController
public function createAction(Request $request)
{
$entity = new Tasks();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tasks_show', array('id' => $entity->getId())));
}
return $this->render('TestBundle:Tasks:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
First you need to get project that you want to assign tasks to it. For example you can send it via Request $request
then use it to query for Project Object
then assign task to this object.
public function createAction(Request $request)
{
$entity = new Tasks();
// doctrine entity manager
$em = this->getDoctrine()->getManager();
// get project_id from query string
$project_id = $request->get('project_id');
// query database for project object
$project = $em->getRepository("TestBundle:Project")->find($project_id);
// assign task to project object
$entity->setProject($project);
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tasks_show', array('id' => $entity->getId())));
}
return $this->render('TestBundle:Tasks:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
Also newAction()
is better place to do this.
I hope this helps.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments