Question

I am currently attempting to add a role to a user account using Symfony2 / FOSUserBundle.

Following the examples, and previous SO questions I have the following in my controller:

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

However when running the method I get the following error:

FatalErrorException: Error: Call to a member function addRole() on a non-object in .....\MyVendor\MyBundle\Controller\DefaultController.php line 52

Apologies if I've missed something obvious - this is my first Symfony2 project.

Was it helpful?

Solution

findBy() returns an array. Try replacing it with findOneBy()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top