在sonata管理包中存储登录的用户数据


Store Logged in user data in sonata admin bundle

在Sonata Admin Bundle中,有一个注册表单。管理员和超级管理员可以使用该注册表单创建用户。一切正常。但是,现在我想跟踪谁(admin或超级管理员id)创建了这个用户。所以我想存储登录的用户id。在商业实体中:

/**
* Set createdBy
*
* @param integer $createdBy
* @return Commercant
*/
public function setCreatedBy($createdBy)
{
 $this->createdBy = $createdBy;
 return $this;
}
/**
* Get createdBy
*
* @return integer
*/
public function getCreatedBy()
{
  return $this->createdBy;
}

在sonata管理类中,我放置了以下代码:

 public function preUpdate($commercant)
{
 $objUser = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
    if(!empty($objUser)) {
        $commercant->setCreatedBy($objUser->getId());
    }
}

但是什么也没发生。

试试这个:

public function prePersist($commercant)
{
    parent::prePersist($commercant);
    $isSuperAdmin = $this->getConfigurationPool()->getContainer()->get('security.context')->isGranted('ROLE_SUPER_ADMIN');
    $isAdmin = $this->getConfigurationPool()->getContainer()->get('security.context')->isGranted('ROLE_ADMIN');
    if($isAdmin || $isSuperAdmin) {
        $objUser = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
        if(!empty($objUser)) {
            $commercant->setCreatedBy($objUser->getId());
        }
    }
}