插入外键值

时间:2015-02-13 10:09:50

标签: php symfony

我有两个实体项目和任务。任务的project_id值与项目id一起映射。每次为特定项目创建新任务时,应设置Task表中的project_id。除了使用隐藏的输入字段表单之外,还有其他方法吗?

TaskController的createAction

  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(),
    ));
}

2 个答案:

答案 0 :(得分:0)

是的,在您处理表单的控制器操作中调用setProject($project)方法

答案 1 :(得分:0)

首先,您需要获得要为其分配任务的项目。 例如,您可以通过Request $request发送它,然后使用它来查询Project 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(),
    ));
}

同样newAction()是更好的地方。

我希望这会有所帮助。