保存当前用户Symfony2

时间:2016-01-14 06:26:19

标签: symfony fosuserbundle

我通过Symfony2 crud生成器创建了一个表单。我有一个实际上与当前实体无关的用户,我希望它自动将当前用户创建的字段保存为其值。你是怎么做到的?我试过了

$entity = new Department();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
       // var_dump($userId);
        //die();
        $user = $this->container->get('security.context')->getToken()->getUser();
        $userId = $user->getUsername();
          var_dump($userId);
        die();//check if user not empty in this case, it return username returns current username
        $entity->$user;
        $em->persist($entity);
        $em->flush();

1 个答案:

答案 0 :(得分:0)

检查我的评论:

 $user = $this->container->get('security.context')->getToken()->getUser();
            $userId = $user->getUsername();
              var_dump($userId);
            die(); // This finish the script remove if you want to execute the rest of the script
            $entity->$user; //This does nothing change by the next line
            $entity->user = $user; //user for user object or userId if you want to store the username
            $em->persist($entity);
            $em->flush();