【问题标题】:Pass userId to from set default to current user将 userId 从设置默认值传递给当前用户
【发布时间】:2012-04-19 10:11:46
【问题描述】:

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

//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');
  }
}

【问题讨论】:

    标签: php symfony-1.4 sfguard


    【解决方案1】:

    在不了解您如何通过操作或通过 $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 在用户上下文。

    【讨论】:

    • 抱歉没有正确启动问题。这是通过操作初始化表单的代码。我真正想要的是将当前用户传递给表单。
    • 不用担心。用您自己的方式更新帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多