我目前正在尝试使用Symfony2 / FOSUserBundle为用户帐户添加角色。
按照示例和之前的SO问题,我在控制器中有以下内容:
namespace MyVendor\MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MyVendor\MyBundle\Entity\Account;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
private function addRole($role, $username)
{
//Get the enity manager
$em = $this->getDoctrine()->getManager();
//Get the user with name admin
$dbuser = $em->getRepository("MyVendor\UserBundle\Entity\User")->findBy(Array("username" => $username));
//Set the role
$dbuser->addRole('ROLE_BASIC_TRIAL');
//Save it to the database
$em->persist($dbuser);
$em->flush();
}
然而,在运行该方法时,我收到以下错误:
FatalErrorException: Error: Call to a member function addRole() on a non-object in .....\MyVendor\MyBundle\Controller\DefaultController.php line 52
如果我错过了一些明显的东西,请道歉 - 这是我的第一个Symfony2项目。
答案 0 :(得分:1)
findBy()返回一个数组。尝试用findOneBy()
替换它