1
votes

FatalErrorException: Error: Call to a member function getId() on a non-object in /home/project/src/Sample/MainBundle/Controller/SampleLogController.php line 19

I am using Symfony v.2.3 and I kept getting this error today.

Here is my controller:

public function NewAction(Request $request){
    $user = $this->getUser()->getId();
    //var_dump($user);
    $repository = $this->getDoctrine()
    ->getRepository('SampleMainBundle:SampleLog');
    $sample_repository = $repository->findByUser($user);
    //...
}

MyEntities:

class SampleLog
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @var integer
    *
    * @ORM\Column(name="user", type="integer")
    */
    protected $user;

    //...

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }


     public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

   /**
     * Get userid
     *
     * @return integer 
     */
    public function getUser()
    {
        return $this->user;
    }

    //...
}
1
getUser does not return an object if the user has not been authenticated i.e. is not logged in.Cerad
@Cerald how am i gonna do that sir? how am i gonna solve it :)Uc.IT_samuel
In guest user OR not authenticated user in action "NewAction" You will get this error. You have to check first if user object exists or not, than redirect to other action OR do you logic.Suf_Malek
@SufiyanMalek Thanks for the idea. I just forgot to login my test account .I thought my account were logged in but its not. :)Uc.IT_samuel
@Uc.IT_samuel pls accept my answer.Suf_Malek

1 Answers

1
votes

In guest user OR not authenticated user in action "NewAction" You will get this error. You have to check first if user object exists or not, than redirect to other action OR do you logic.