我有一个实体“品牌”如下
我想将当前登录的用户ID插入此品牌表,我的控制器代码如下,ID和名称工作正常并插入表中,请告诉我应该添加什么以将当前用户ID插入在db表中,用户可以有很多品牌。
public function newBrandAction(Request $request)
{
$brand = new brand();
$form = $this->createFormBuilder($brand)
->add('name',TextType::class,array('label'=>'Brand Name'))
->add('save',SubmitType::class, array('label'=>'Add Brand'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($brand);
$em->flush();
return $this->render('coreBundle:layouts:newBrand.html.twig',
array('form'=>$form->createView(),));
}
return $this->render('coreBundle:layouts:newBrand.html.twig',
array('form'=>$form->createView(),));
}
答案 0 :(得分:1)
您需要在表单中添加这样的用户关系:
->add('user', EntityType::class, array(
'class' => 'YourBundle:User',
'choice_label' => 'username' //here you can insert what field you want or you can remove this option
))
显然,您需要将EntityType
添加到控制器的use
我建议你阅读这个链接:
要仅插入当前用户,您可以在保留
之前执行此操作$user = $this->container->get('security.token_storage')->getToken()->getUser();
$brand->setUser($user);
答案 1 :(得分:0)
我想实际将user_id插入数据库表而不在表单上显示任何选项,我已按以下方式完成此操作。
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$em->persist($brand);
$brand->setUserId($user);
$em->flush();
/* */
}
答案 2 :(得分:0)
使用StofDoctrineExtensions Bundle
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\ManyToOne(targetEntity="User")
* @Gedmo\Blameable(on="create")
*/
private $creator;