2012-04-19 205 views
0

快速提问。我使用symfony1.4与Doctrine ORM和sfGuardDoctrinePlugin。我有一个名为'任务'的symfony表单。我希望将userId字段(如果用户表的FK设为Id)默认设置为当前记录的用户。我怎样才能做到这一点?将userId设置为从默认设置为当前用户

//apps/myapp/modules/task/actions 

class taskActions extends sfActions 
{ 
    public function executeNew(sfWebRequest $request) 
    { 
    $this->form = new taskForm(); 
    } 

    public function executeCreate(sfWebRequest $request) 
    { 
    $this->forward404Unless($request->isMethod(sfRequest::POST)); 

    $this->form = new taskForm(); 

    $this->processForm($request, $this->form); 

    $this->setTemplate('new'); 
    } 
} 

回答

0

的棘手没有看到你是如何通过行动设立的形式,或者通过$form->configure(),但你可以使用此访问当前用户ID来回答种类:

$currentUserId = sfContext::getInstance()->getUser()->getGuardUser()->getId(); 

- 更新 -

根据您的更新,看起来taskForm不是基于模型对象,否则您将通过构造函数传递一个对象,因此它必须是自定义窗体。有一对夫妇的方法对皮肤这只猫,你可以通过构造函数传递用户对象,或者您可以通过一个公共的访问设定的值,就像这样:

class taskForm 
{ 
    protected $user; 

    public function setUser($user) 
    { 
     $this->user = $user; 
    } 

    public function getUser() 
    { 
     return $this->user; 
    } 

    public function configure() 
    { 
     // This should output the current user id which demonstrates that you now 
     // have access to user attributes in your form class 
     var_dump($this->getUser()->getGuardUser()->getId()); 
    } 
} 

并设置它:

public function executeNew(sfWebRequest $request) 
{ 
    $this->form = new taskForm(); 

    $this->form->setUser($this->getUser()); 
} 

另一种方式,你可能能够做到这一点是直接通过构造函数传递用户对象,那么你可以使用$this->getObject()->getUser()而在形式引用它,虽然我不建议这样做,因为它在用户中强制taskForm上下文。

+0

对不起,没有启动问题的权利。以下是通过操作初始化表单的代码。我真正想要的是将当前用户传递给表单。 – 2012-04-19 02:00:42

+0

不用担心。用一种方式更新后的职位。 – 2012-04-19 02:12:03

相关问题