PHP: Call to a member function .... on a non-object - php

hello I'm having trouble with:
public function isAdmin()
{
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
it causes: Call to a member function getRoleId() on a non-object
please guys, help. thanks
classes:
class Role implements HierarchicalRoleInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Store role kind.
* Possible user kinds: 'guest' (not signed in),
'user' (default for signed in user), 'admin'.
* #var string
* #ORM\Column(type="string", length=255,
unique=true, nullable=true)
*/
protected $roleId;
/**
* Store role parent for inheritance measure.
* #var Role
* #ORM\ManyToOne(targetEntity="User\Entity\Role")
*/
protected $parent;
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get role kind.
* #return string
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* Set role kind.
* #param string $roleId
* #return void
*/
public function setRoleId($roleId)
{
$this->roleId = (string) $roleId;
}
/**
* Get parent role
* #return Role
*/
public function getParent()
{
return $this->parent;
}
/**
* Set parent role.
* #param Role $parent
* #return void
*/
public function setParent(Role $parent)
{
$this->parent = $parent;
}
}
class User implements UserInterface, ProviderInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Store username.
* #var string
* #ORM\Column(type="string", length=255, unique=true)
*/
protected $username;
/**
* Store email.
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* Store displayName.
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* Store password.
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* Store state.
* #var int
*/
protected $state;
/**
* Store mark.
* #var float
*/
protected $mark;
/**
* Store roles collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="User\Entity\Role")
* #ORM\JoinTable(name="users_roles",
* joinColumns={
#ORM\JoinColumn(
name="user_id",
referencedColumnName="id"
)
},
* inverseJoinColumns={
#ORM\JoinColumn(
name="role_id",
referencedColumnName="id"
)
}
* )
*/
protected $roles;
/**
* Store albums collection
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Album\Entity\Album", mappedBy="user",
cascade={"all"})
*/
protected $albums;
/**
* Store comments collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Comment\Entity\Comment", mappedBy="user",
cascade={"all"})
*/
protected $comments;
/**
* Store marks collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Mark\Entity\Mark", mappedBy="user",
cascade={"all"})
*/
protected $marks;
/**
* Initialies collections.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->albums = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->marks = new ArrayCollection();
}
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
* #return string
*/
public function getUsername()
{
return htmlspecialchars($this->username);
}
/**
* Set username.
* #param string $username
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
* #param string $email
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
* #param string $displayName
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
* #param string $password
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
* #param int $state
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
public function getFirstRole() {
$roles = $this->getRoles();
$firstRole = $roles[0];
return $firstRole;
}
/**
* Get comments collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Get marks collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getMarks()
{
return $this->marks;
}
/**
* Add a role to user.
* #param Role $role
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get albums.
* #return \Doctrine\Common\Collections\Collection
*/
public function getAlbums()
{
return $this->albums;
}
public function isAdmin(){
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
/**
* Calculate user mark.
* #return float
*/
public function mark()
{
if (!$this->mark) {
$albums = $this->getAlbums();
$result = 0;
foreach ($albums as &$album) {
$result += $album->mark();
}
$this->mark = $result;
}
return $this->mark;
}
}
anyone?
(writing this becaue it says my post is mostly code)
(writing this becaue it says my post is mostly code)

/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
Collections are not accessed by [0], they are Collection objects, use like this:
public function getFirstRole() {
return $this->roles->first();
}
#h2ooooooo gave this helpful link to the docs, containing all methods of the collection: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html
You can compare ID with an ID (integer), or string by string,
but the best is to compare Entities to keep the whole system integral:
public function isAdmin() {
$role = $this->getFirstRole();
$admin = $entityManager
->getRepository('User\Entity\Role')
->findOneByName('admin');
if ($role === $admin) {
return true;
} else {
return false;
}
}

it seems that $this->getFirstRole() returned user role as string. you just need to compare it as string.
try this:
public function isAdmin()
{
$role = $this->getFirstRole();
return $role == "admin" ? true : false;
}

Related

Access User Scores on Many-to-One Relationship using Symfony 3

I'm creating an app that keeps user scores in the database based on questions they solve. I have User, Problem and Submission entities. For all of them I have One-to-Many relationship from the User entity. The problem entity has the point field that holds the score of a problem. I'm trying to retrieve all users with their total points.
Here is my controller;
$userService = $this->container->get('userservice');
$users = $userService->findAll();
foreach ($users as $user){
$usersWPoints = $user->getSubmissions()->getProblemId()->getPoints;
}
However this returns the following error;
Attempted to call an undefined method named "getProblemId" of class "Doctrine\ORM\PersistentCollection".
Here are my models
User.php
/**
* Class User
* #package AppBundle\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
* #ORM\HasLifecycleCallbacks()
* #UniqueEntity(fields="username", message="Email already taken")
*
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid email address")
* #Assert\Email()
*/
private $username;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid email address")
*/
private $usrname;
/**
* #Assert\NotBlank()
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* The below length depends on the "algorithm" you use for encoding
* the password, but this works well with bcrypt.
*
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(message="Please enter a valid name")
*/
private $fullname;
/**
* #var array
* #ORM\Column(name="roles", type="json_array")
*/
protected $roles;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Problem", mappedBy="createdby")
*/
protected $problems;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Feed", mappedBy="createdby")
*/
protected $feeds;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Comment", mappedBy="createdby")
*/
protected $comments;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Submission", mappedBy="user_id")
*/
protected $submissions;
// other properties and methods
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
// other methods, including security methods like getRoles()
/**
* #return array
*/
public function getRoles()
{
return $this->roles;
}
public function setRoles(array $roles){
$this->roles = $roles;
return $this;
}
/**
* #return mixed
*/
public function getFullname()
{
return $this->fullname;
}
/**
* #param mixed $fullname
*/
public function setFullname($fullname)
{
$this->fullname = $fullname;
}
/**
* #return mixed
*/
public function getUsrname()
{
return $this->usrname;
}
/**
* #param mixed $usrname
*/
public function setUsrname($usrname)
{
$this->usrname = $usrname;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getSubmissions()
{
return $this->submissions;
}
Problem.php
/**
* Class Problem
* #package AppBundle\Entity
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProblemRepository")
* #ORM\Table(name="problem")
* #ORM\HasLifecycleCallbacks()
*
*/
class Problem
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=True)
* #Assert\NotBlank(message="Please enter a valid title")
*/
protected $title;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid description")
*/
protected $description;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid value")
*/
protected $points;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid flag")
*/
protected $flag;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Please enter a valid value")
*/
protected $category;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="problems")
* #ORM\JoinColumn(name="createdby", referencedColumnName="id")
*/
protected $createdby;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Submission", mappedBy="problem_id")
*/
protected $submissions;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(type="string", length=255, unique=false,)
*/
protected $slug;
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* #return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* #param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return mixed
*/
public function getPoints()
{
return $this->points;
}
/**
* #param mixed $points
*/
public function setPoints($points)
{
$this->points = $points;
}
/**
* #return mixed
*/
public function getFlag()
{
return $this->flag;
}
/**
* #param mixed $flag
*/
public function setFlag($flag)
{
$this->flag = $flag;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getCreatedby()
{
return $this->createdby;
}
/**
* #param mixed $createdby
*/
public function setCreatedby($createdby)
{
$this->createdby = $createdby;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set slug
*
* #param string $slug
*
* #return Problem
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* #return mixed
*/
public function getSubmissions()
{
return $this->submissions;
}
/**
* #param mixed $submissions
*/
public function setSubmissions($submissions)
{
$this->submissions = $submissions;
}
}
Submission.php
class Submission
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Problem", inversedBy="submissions")
* #ORM\JoinColumn(name="problem_id", referencedColumnName="id")
*/
protected $problem_id;
/**
* #ORM\Column(type="boolean")
*/
protected $correct = false;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="submissions")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user_id;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Flag cannot be blank")
*/
protected $submission_flag;
/**
* #return mixed
*/
public function getProblemId()
{
return $this->problem_id;
}
/**
* #param mixed $problem_id
*/
public function setProblemId($problem_id)
{
$this->problem_id = $problem_id;
}
/**
* #return mixed
*/
public function getCorrect()
{
return $this->correct;
}
/**
* #param mixed $correct
*/
public function setCorrect($correct)
{
$this->correct = $correct;
}
/**
* #return mixed
*/
public function getUserId()
{
return $this->user_id;
}
/**
* #param mixed $user_id
*/
public function setUserId($user_id)
{
$this->user_id = $user_id;
}
/**
* #return mixed
*/
public function getSubmissionFlag()
{
return $this->submission_flag;
}
/**
* #param mixed $submission_flag
*/
public function setSubmissionFlag($submission_flag)
{
$this->submission_flag = $submission_flag;
}
}
Any suggestions on accessing each user and their total points would be highly appreciated.
getSubmissions() returns collenction and getProblemId() is method of Submissions.
So as soon as you have many Submissions fo each user - i would create some getTotalPoints() method for User where you can run in foreach.
This kind of way:
public function getTotalPoints()
{
$submissions = $this->getSubmissions();
$points = 0;
foreach ($submissions as $submission) {
$points += $submission->getProblemId()->getPoints();
}
return $points;
}
You could do something like this:
$userService = $this->container->get('userservice');
$users = $userService->findAll();
$pointPerUser = array();
foreach ($users as $user){
$userSubmissions = $user->getSubmissions();
$pointPerUser[$user->getId()] = 0;
foreach ($userSubmissions as $userSubmission) {
// Probably here you want to check if the submission is correct
$pointPerUser[$user->getId()] += $userSubmission->getProblemId()->getPoints();
}
}
By the way, the submission attribute shouldn't be $problem_id but $problem, and the method is getProblem(), as you are getting a Problem instance, not an id. The field name for the table is ok, as you are storing an id.

unexpected behaviour following changing entity relationships

my nightmare of a day continues.....
after implimenting a successful solution in an earlier thread where I need to alter my inter-entity relationships I am now getting this error when I try to log a user into the app:
CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\UndefinedMethodException: "Attempted to call method "getRole" on class "Closure"." at C:\Dropbox\xampp\htdocs\etrack3\src\Ampisoft\Bundle\etrackBundle\Entity\Users.php line 234
I changed from a manyToMany relationship, to a manyToOne/OneToMany between a Users/Roles entity.
Ive read that serialize could cause the issue but Ive taken it out and it didnt make any difference. The remnants of the serialize required methods are still in there so please ignore (unless they are the issue).
Please could someone tell me what Ive done wrong? Im wondering if its best to scrap all the database tables and start again!!!!
here is the entity class.
/**
* user
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Ampisoft\Bundle\etrackBundle\Entity\UsersRepository")
*/
class Users implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=25, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=64)
*/
private $password;
/**
* #ORM\Column(name="firstname", type="string", length=25)
*/
private $firstname;
/**
* #ORM\Column(name="surname", type="string", length=25)
*/
private $lastname;
/**
* #var boolean
*
* #ORM\Column(name="isActive", type="boolean")
*/
private $isActive = 1;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* #var \DateTime
*
* #ORM\Column(name="lastLogged", type="string")
*/
private $lastLogged = '-0001-11-30 00:00:00';
/**
* #var string;
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #ORM\ManyToOne(targetEntity="Roles", inversedBy="users")
*
*/
private $roles;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Id
*
* #return integer
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set username
*
* #param string $username
* #return user
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return user
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return user
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set email
*
* #param string $email
* #return user
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set lastLogged
*
* #param \DateTime $lastLogged
* #return user
*/
public function setLastLogged($lastLogged)
{
$this->lastLogged = $lastLogged;
return $this;
}
/**
* Get lastLogged
*
* #return \DateTime
*/
public function getLastLogged()
{
return $this->lastLogged;
}
public function __construct()
{
$this->roles = new ArrayCollection();
$this->isActive = true;
}
/**
* #inheritDoc
*/
public function getRoles()
{
$roles = array();
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
/**
* #param $roles
* #return $this
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #inheritDoc
*/
public function getSalt()
{
return $this->salt;
}
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* Add roles
*
* #param \Ampisoft\Bundle\etrackBundle\Entity\Roles $roles
* #return users
*/
public function addRoles(Roles $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \Ampisoft\Bundle\etrackBundle\Entity\Roles $roles
*/
public function removeRoles(Roles $roles)
{
$this->roles->removeElement($roles);
}
/**
* Set firstname
*
* #param string $firstname
* #return users
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return users
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* #see \Serializable::serialize()
*/
/**
* Serializes the content of the current User object
* #return string
*/
public function serialize()
{
return \json_encode(
array($this->username, $this->password, $this->salt,
$this->roles, $this->id));
}
/**
* Unserializes the given string in the current User object
* #param serialized
*/
public function unserialize($serialized)
{
list($this->username, $this->password, $this->salt,
$this->roles, $this->id) = \json_decode(
$serialized);
}
}
update 1
this has worked but produced a new error Im going to move it to a new question when the post timer lets me.
Catchable Fatal Error: Argument 4 passed to Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::__construct() must be of the type array, object given, called in C:\Dropbox\xampp\htdocs\etrack3\vendor\symfony\symfony\src\Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider.php on line 96 and defined
HI I think what you want is not this
public function getRoles()
{
$roles = array();
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
but this
public function getRoles()
{
return $this->roles;
}
Roles should be an ArrayCollection already, so calling getRole on the ( I assume ) Role class seems to be possible the issue.
If you are using an IDE such as Eclipse then the class is Doctrine\Common\Collections\ArrayCollection; this should be your collection of Roles, I would suggest also is you are using an IDE to do something like this ( for type hinting )
//... at the top of the class file before the class deceleration
use Doctrine\Common\Collections\ArrayCollection;
/**
* #param ArrayCollection $roles
*/
public function setRoles(ArrayCollection $roles)
{
//.. type cast the input to allow only use of ArrayCollection class
$this->roles = $roles;
}
/**
* #return ArrayCollection
*/
public function getRoles()
{
return $this->roles;
}
Also there is a good chance you are setting $this->roles to be a standard array at some point. You should always type cast your input to a specific class if it can only accept that type of class to rule out errors such as using a plain array.
Last thing, is generally protected for the properties are preferred because latter you can extend the class, it's not accessible outside the class much like private, but unlike private it is accessible in inheriting classes.

Symfony2 - Not able to assign Roles to user (roles array is empty)

I am new to Symfony2. I am not using FOS UserBundle to implement security.
Followed the Load user documentation in the main website of Symfony.
When I try to see the array of User entity it's showing empty for particular user as shown below
[roles:Acme\UserBundle\Entity\User:private] =>
Doctrine\Common\Collections\ArrayCollection Object (
[_elements:Doctrine\Common\Collections\ArrayCollection:private] =>
Array ( ) )
My User Entity class is
<?php
namespace Acme\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Acme\UserBundle\Entity\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Acme\UserBundle\Entity\Role;
/**
* Acme\Bundle\UserRegistrationBundle\Entity\User
*
* #ORM\Table(name="acme_users")
* #ORM\Entity(repositoryClass="Acme\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $fname;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $lname;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=20)
*/
private $gender;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $profession;
/**
* #ORM\Column(type="date")
*/
private $date_of_birth;
/**
* #ORM\Column(type="integer")
*/
private $country_id;
/**
* #ORM\Column(type="integer")
*/
private $state_id;
/**
* #ORM\Column(type="integer")
*/
private $city_id;
/**
* #ORM\Column(type="string", length=20)
*/
private $phone_number;
/**
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
* #ORM\Column(type="integer")
*/
private $is_lock;
/**
* #ORM\Column(type="integer")
*/
private $failed_attempt;
/**
* #ORM\Column(type="string", length=32)
*/
private $salt;
/**
* #ORM\ManyToMany(targetEntity="Role",inversedBy="users")
* #var ArrayCollection $roles;
*/
private $roles;
public function __construct()
{
$this->status = true;
$this->salt = md5(uniqid(null, true));
$this->roles = new ArrayCollection();
}
/**
* Get roles (array)
*
* #return array
*/
public function getRoles()
{
return $this->roles->toArray();
}
/**
* Get user_id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fname
*
* #param string $fname
* #return User
*/
public function setFname($fname)
{
$this->fname = $fname;
return $this;
}
/**
* Get fname
*
* #return string
*/
public function getFname()
{
return $this->fname;
}
/**
* Set lname
*
* #param string $lname
* #return User
*/
public function setLname($lname)
{
$this->lname = $lname;
return $this;
}
/**
* Get lname
*
* #return string
*/
public function getLname()
{
return $this->lname;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set gender
*
* #param string $gender
* #return User
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set profession
*
* #param string $profession
* #return User
*/
public function setProfession($profession)
{
$this->profession = $profession;
return $this;
}
/**
* Get profession
*
* #return string
*/
public function getProfession()
{
return $this->profession;
}
/**
* Set date_of_birth
*
* #param \DateTime $dateOfBirth
* #return User
*/
public function setDateOfBirth($dateOfBirth)
{
$this->date_of_birth = $dateOfBirth;
return $this;
}
/**
* Get date_of_birth
*
* #return \DateTime
*/
public function getDateOfBirth()
{
return $this->date_of_birth;
}
/**
* Set country_id
*
* #param integer $countryId
* #return User
*/
public function setCountryId($countryId)
{
$this->country_id = $countryId;
return $this;
}
/**
* Get country_id
*
* #return integer
*/
public function getCountryId()
{
return $this->country_id;
}
/**
* Set state_id
*
* #param integer $stateId
* #return User
*/
public function setStateId($stateId)
{
$this->state_id = $stateId;
return $this;
}
/**
* Get state_id
*
* #return integer
*/
public function getStateId()
{
return $this->state_id;
}
/**
* Set city_id
*
* #param integer $cityId
* #return User
*/
public function setCityId($cityId)
{
$this->city_id = $cityId;
return $this;
}
/**
* Get city_id
*
* #return integer
*/
public function getCityId()
{
return $this->city_id;
}
/**
* Set phone_number
*
* #param string $phoneNumber
* #return User
*/
public function setPhoneNumber($phoneNumber)
{
$this->phone_number = $phoneNumber;
return $this;
}
/**
* Get phone_number
*
* #return string
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* Set status
*
* #param boolean $status
* #return User
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
/**
* Set is_lock
*
* #param integer $isLock
* #return User
*/
public function setIsLock($isLock)
{
$this->is_lock = $isLock;
return $this;
}
/**
* Get is_lock
*
* #return integer
*/
public function getIsLock()
{
return $this->is_lock;
}
/**
* Set failed_attempt
*
* #param integer $failedAttempt
* #return User
*/
public function setFailedAttempt($failedAttempt)
{
$this->failed_attempt = $failedAttempt;
return $this;
}
/**
* Get failed_attempt
*
* #return integer
*/
public function getFailedAttempt()
{
return $this->failed_attempt;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Add roles
*
* #param \Autograph\UserBundle\Entity\Role $roles
* #return User
*/
public function addRole(\Autograph\UserBundle\Entity\Role $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \Autograph\UserBundle\Entity\Role $roles
*/
public function removeRole(\Autograph\UserBundle\Entity\Role $roles)
{
$this->roles->removeElement($roles);
}
public function eraseCredentials() {
}
public function getUsername() {
}
public function serialize() {
}
public function unserialize($serialized) {
}
}
My Role Entity Class is
<?php
// src/Acme/UserBundle/Entity/Role.php
namespace Acme\UserBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="acme_roles")
* #ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*
* #var string $role
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*
* #var ArrayCollection $users
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
/**
* Set role
*
* #param string $role
* #return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
// ... getters and setters for each property
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add users
*
* #param \Autograph\UserBundle\Entity\User $users
* #return Role
*/
public function addUser(\Autograph\UserBundle\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* #param \Autograph\UserBundle\Entity\User $users
*/
public function removeUser(\Autograph\UserBundle\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
What is wrong?

Updating a field in a table from a join OneToOne Symfony2 / Doctrine 2

I have a problem with Doctrine2 in Symfony2 and two relationed entities.
I have a class Users
class Users
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=50)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=50)
*/
private $password;
/**
* #var boolean
*
* #ORM\Column(name="type", type="boolean")
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="first_name", type="string", length=100)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=100)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="tel", type="string", length=255)
*/
private $tel;
/**
* #var string
*
* #ORM\Column(name="url_img", type="string", length=255)
*/
private $urlImg;
/**
* #var string
*
* #ORM\Column(name="company", type="string", length=255)
*/
private $company;
/**
* #ORM\OneToOne(targetEntity="Providers", mappedBy="userId", cascade={"persist"})
*/
protected $provider;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set type
*
* #param boolean $type
* #return Users
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return boolean
*/
public function getType()
{
return $this->type;
}
/**
* Set idPrest
*
* #param integer $idPrest
* #return Users
*/
public function setIdPrest($idPrest)
{
$this->idPrest = $idPrest;
return $this;
}
/**
* Get idPrest
*
* #return integer
*/
public function getIdPrest()
{
return $this->idPrest;
}
/**
* Set idEmbaucher
*
* #param integer $idEmbaucher
* #return Users
*/
public function setIdEmbaucher($idEmbaucher)
{
$this->idEmbaucher = $idEmbaucher;
return $this;
}
/**
* Get idEmbaucher
*
* #return integer
*/
public function getIdEmbaucher()
{
return $this->idEmbaucher;
}
/**
* Set email
*
* #param string $email
* #return Users
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set firstName
*
* #param string $firstName
* #return Users
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
* #return Users
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set tel
*
* #param string $tel
* #return Users
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set urlImg
*
* #param string $urlImg
* #return Users
*/
public function setUrlImg($urlImg)
{
$this->urlImg = $urlImg;
return $this;
}
/**
* Get urlImg
*
* #return string
*/
public function getUrlImg()
{
return $this->urlImg;
}
/**
* Set company
*
* #param string $company
* #return Users
*/
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* #return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set provider
*
* #param Providers $provider
* #return Users
*/
public function setProvider($provider = null)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return Providers
*/
public function getProvider()
{
return $this->provider;
}
}
in relation with class provider on OneToOne (inheriting)
class Providers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="Users", inversedBy="provider")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $userId;
/**
* #ORM\OneToOne(targetEntity="Advertisement", mappedBy="provider")
*/
protected $advertisement;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* #param \leBonCoinDesServices\MainBundle\Entity\Users $userId
* #return Providers
*/
public function setUserId($userId = null)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return \leBonCoinDesServices\MainBundle\Entity\Users
*/
public function getUserId()
{
return $this->userId;
}
}
I just want to get the fields user_id created from the relationship for be able to when I create a user get the id of this one and give it to the user_id field.
And when I test my controller to create a user and a provider :
public function newUserAction()
{
$user = new Users();
$user->setUsername("gokusan");
$user->setPassword("test");
$user->setType("p");
$user->setEmail("test#msn.com");
$user->setFirstName("KHALIL");
$user->setLastName("Ahmed");
$user->setTel("0142021148");
$user->setUrlImg("img/test/");
$user->setCompany("Push&Pull");
$this->getDoctrine()->getEntityManager()->persist($user);
$this->getDoctrine()->getEntityManager()->flush();
$provider = new Providers();
$id = $user->getId();
$provider->setUserId($id);
$this->getDoctrine()->getEntityManager()->persist($provider);
$this->getDoctrine()->getEntityManager()->flush();
die("User Added");
}
that puts me error :
Warning: spl_object_hash() expects parameter 1 to be object, integer given in F:\Programs Files\Program Files\wamp\www\leboncoindesservices\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 1367
Your Providers::setUserId($userId) expects $userId to be of type \leBonCoinDesServices\MainBundle\Entity\Users and not of type integer. So you should be able to pass your Users object to the $provider like
$user = new Users();
...
$provder = new Providers();
...
$provider->setUserId($user);

php and twig syntax

I have the following code to extract the username of an owner object. The Owner object is essentially the owner of the shop. Here's how it's defined in the Shop class.
/**
* Set owner
*
* #param User $owner
* #return Shop
*/
public function setOwner(User $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return User
*/
public function getOwner()
{
return $this->owner;
}
/**
As you can see the owner returns a User object. However when I do .username to the User class I always get undefined. Why is this?
"<%= '/profile/'+item.get('shop').owner.username %>">
When I do the following:
"<%= '/profile/'+item.get('shop').name %>">
it prints out just fine.
Here's some more code on the Shop:
class Shop
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Exclude()
* #ORM\Column(name="isVisible", type="boolean")
*/
private $isVisible = false;
/**
* #ORM\OneToOne(targetEntity="Shopious\MainBundle\Entity\ShopLogo", mappedBy="shop", cascade={"persist","remove"})
*/
protected $shoplogo;
/**
* #Assert\NotBlank(message="Shope name should not be blank")
* #ORM\Column(name="name", type="string", length=100, unique=true)
*/
protected $name;
/**
* Assert\NotBlank(message="Description should not be blank")
* #ORM\Column(name="description", type="string", length=350, nullable=true)
*/
protected $description = "";
/**
* #ORM\Column(name="tags", type="text",nullable=true)
*/
protected $tags = "";
/**
* #ORM\OneToMany(targetEntity="Shopious\MainBundle\Entity\Product", mappedBy="shop", cascade={"remove","persist"})
*/
protected $products;
/**
* #Exclude()
* #ORM\OneToOne(targetEntity="Shopious\UserBundle\Entity\User", inversedBy="shop")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
protected $owner;
/**
* #Exclude()
* #ORM\OneToOne(targetEntity="Shopious\MainBundle\Entity\PaymentInfo", inversedBy="shop", cascade={"persist","remove"})
* #ORM\JoinColumn(name="paymentInfo_id", referencedColumnName="id" , onDelete="CASCADE")
*/
protected $paymentInfo;
/**
*
* #ORM\OneToMany(targetEntity="Shopious\MainBundle\Entity\ShopTestimonial", mappedBy="shop", cascade={"persist","remove"})
*/
protected $testimonials;
public function __toString()
{
return $this->shopname;
}
/**
* #ORM\PrePersist
*/
public function initialisation()
{
$this->shoplogo = new ShopLogo();
$this->shoplogo->setShop($this);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set owner
*
* #param User $owner
* #return Shop
*/
public function setOwner(User $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return User
*/
public function getOwner()
{
return $this->owner;
}
/**
* Constructor
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Set shopname
*
* #param string $shopname
* #return Shop
*/
public function setName($shopname)
{
$this->name = $shopname;
//return $this;
}
/**
* Get shopname
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Shop
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Add products
*
* #param Product $products
* #return Shop
*/
public function addProduct(Product $products)
{
$this->products[] = $products;
return $this;
}
/**
* Remove products
*
* #param Product $products
*/
public function removeProduct(Product $products)
{
$this->products->removeElement($products);
}
/**
* Get products
*
* #return Collection
*/
public function getProducts()
{
return $this->products;
}
public function getPaymentInfo()
{
return $this->paymentInfo;
}
public function setPaymentInfo(\Shopious\MainBundle\Entity\PaymentInfo $paymentInfo)
{
$this->paymentInfo = $paymentInfo;
}
/**
* Set tags
*
* #param string $tags
* #return Shop
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set shoplogo
*
* #param Shopious\MainBundle\Entity\ShopLogo $shoplogo
* #return Shop
*/
public function setShoplogo(\Shopious\MainBundle\Entity\ShopLogo $shoplogo = null)
{
$this->shoplogo = $shoplogo;
return $this;
}
/**
* Get shoplogo
*
* #return Shopious\MainBundle\Entity\ShopLogo
*/
public function getShoplogo()
{
return $this->shoplogo;
}
/**
* Add testimonials
*
* #param \Shopious\MainBundle\Entity\ShopTestimonial $testimonials
* #return Shop
*/
public function addTestimonial(\Shopious\MainBundle\Entity\ShopTestimonial $testimonials)
{
$this->testimonials[] = $testimonials;
return $this;
}
/**
* Remove testimonials
*
* #param \Shopious\MainBundle\Entity\ShopTestimonial $testimonials
*/
public function removeTestimonial(\Shopious\MainBundle\Entity\ShopTestimonial $testimonials)
{
$this->testimonials->removeElement($testimonials);
}
/**
* Get testimonials
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTestimonials()
{
return $this->testimonials;
}
/**
* Set isVisible
*
* #param boolean $isVisible
* #return Product
*/
public function setIsVisible($isVisible)
{
$this->isVisible = $isVisible;
return $this;
}
/**
* Get isVisible
*
* #return boolean
*/
public function getIsVisible()
{
return $this->isVisible;
}
}
Some code of fetching the data values:
public function getItemsAction()
{
try{
$query = $this->getRequest()->query;
$em = $this->getDoctrine()->getEntityManager();
$items = $em->getRepository('ShopiousMainBundle:Product')->filterBy(
$query->get('category'),
$query->get('tag'),
$query->get('size'),
$query->get('price'),
$query->get('shop'),
$query->get('sort'),
$query->get('page')
);
return $this->Json($items);
}catch(\Exception $ex){
return $this->Json($ex->getMessage(),false);
}
}
I am guessing it is because their is not data for the relationship. It looks like you probably have an item that you are calling a method on to get another object and then calling another method on that object to get yet another object. Since the first call is a proxy object it probably doesn't load the second proxy object data with it. If you look at the data in the data outside the template like in the controller I am guessing it isn't defined there. you might want to make sure that the data is loaded prior to getting to the view. I think that the root of the problem is the initial relationship.
To help you might post some of your controller code where you are getting fetching the data or setting the values.
sounds like class Owner's name is stored into variable "name", not "username"
i think protected $username; doesnot exist only protected $name;
if you want
"<%= '/profile/'+item.get('shop').owner.username %>">
then change
add this to you class first
protected $username[];
public function addUsers(User $user = null)
{
array_push($this->username, $user);
return $this->username;
}
public function getUsers()
{
return $this->username;
}
or a single user
protected $username;
public function addUsers(User $user = null)
{
$this->username= $user;
return $this->username;
}
public function getUsers()
{
return $this->username;
}

Categories