我的格式是这个字段:
->add('taskOwner', null, array(
'label' => $this-> translator ->trans( 'tasks.index.responsible' , array() , 'crm' )))
Symfony将其识别为选择类型(它具有用户的另一个表的外键)。现在我想在已登录用户上设置默认值。我怎么能这样做?我尝试在我的控制器中创建我的类型的新实体,将taskOwner设置到其中,然后通过SetData将其放入表单中,如下所示:
$entity = new Tasks();
$tasksForm = $this->createForm(new TasksType($translator), $entity);
$userId = $this->get('security.context')->getToken()->getUser()->getId();
$user = $this->getDoctrine()->getRepository('CloudAdmBundle:AdmUser')->find($userId);
$task = new Tasks();
$task->setTaskOwner($user);
$tasksForm->setData($task);
要清除所有内容,定义setter:
public function setTaskOwner(\Cloud\AdmBundle\Entity\AdmUser $taskOwner = null)
{
$this->taskOwner = $taskOwner;
return $this;
}
答案 0 :(得分:1)
在创建表单之前执行此操作:
$userId = $this->get('security.context')->getToken()->getUser()->getId();
$user = $this->getDoctrine()->getRepository('CloudAdmBundle:AdmUser')->find($userId);
$entity = new Tasks();
$entity->setTaskOwner($user);
$tasksForm = $this->createForm(new TasksType($translator), $entity);