保存当前用户 Symfony2
Save current user Symfony2
我通过 Symfony2 crud 生成器创建了一个表单。我有一个实际上与当前实体无关的用户,我希望它自动将当前用户的 createdby 字段保存为它的 value.How 你做到了吗?我试过了
$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();
查看我的评论:
$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();
我通过 Symfony2 crud 生成器创建了一个表单。我有一个实际上与当前实体无关的用户,我希望它自动将当前用户的 createdby 字段保存为它的 value.How 你做到了吗?我试过了
$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();
查看我的评论:
$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();