简体   繁体   中英

Store Logged in user data in sonata admin bundle

In Sonata Admin Bundle, there is a registration form. Admin and super admin can create user using that registration form. Everything is working. But, now i want to keep trackwho (admin or super-admin id) created this user.So i want to store logged in user id. in Commercant Entity:

/**
* 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;
}

With this in sonata admin class i placed this code:

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

}

but nothing happen.

Try with this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM