2013-11-22 154 views
0

我有這個場在我的形式:的Symfony 2選擇字段默認值

->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); 

要清除一切,定義二傳手:

public function setTaskOwner(\Cloud\AdmBundle\Entity\AdmUser $taskOwner = null) 
    { 
     $this->taskOwner = $taskOwner; 

     return $this; 
    } 

回答

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);