我通过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();
答案 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();