我正在尝试创建一个任务管理器,我需要能够获取当前登录用户的用户ID,以便在创建任务时,用户ID也会输入到数据库中。我无法让它工作它一直告诉我call to undefined function getUser()
我不认为我必须定义它,我认为它是内置的。
有人可以帮我解决这个问题,非常感谢!
这是创建任务的功能
<?php
namespace Starnes\TaskBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Starnes\TaskBundle\Entity\Task;
use Starnes\TaskBundle\Form\TaskType;
use Starnes\UserBundle\Entity\User;
/**
* Task controller.
*
* @Route("/task")
*/
class TaskController extends Controller
{
/**
* Lists all Task entities.
*
* @Route("/", name="task")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('StarnesTaskBundle:Task')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new Task entity.
*
* @Route("/", name="task_create")
* @Method("POST")
* @Template("StarnesTaskBundle:Task:new.html.twig")
*
*/
public function createAction(Request $request)
{
$user = new User();
$userID = $user->getUser()->getId();
$entity = new Task();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$entity->setUserId($userID);
$em->flush();
return $this->redirect($this->generateUrl('task_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
答案 0 :(得分:20)
简单地写
$user = $this->getUser()->getId();
您获得当前用户的ID
答案 1 :(得分:18)
您不需要创建新的用户对象$user = new User();
,您可以从安全上下文中获取当前登录的用户对象
$user = $this->container->get('security.context')->getToken()->getUser();
$user->getId();
答案 2 :(得分:4)
这对我有用 Symfony 3
function link(scope, element, attrs, ctrl) {
var unbinder = scope.$watch(function () {return ctrl[scope.model] }, function(value) {
if (!value) return;
scope.errorMessagesList = ctrl[scope.model].$error;
unbinder();
})
}
答案 3 :(得分:0)
您可以使用此变量:{{app.user.id}}。
如果没有连接用户ID,则显示已连接的用户ID