Relation Many to Many Bidirectional Symfony 3 - php

I'm using Symfony 3 with Doctrine. I have 2 entities in my application, User and Role. I need to make a bidirectional relationship many to many.
I consulted the doctrine documentation.Here is the code:
class Rol
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=255, unique=true)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="descripcion", type="string", length=255)
*/
private $descripcion;
/**
* #ORM\ManyToMany(targetEntity="Funcionalidad", inversedBy="rolesUsuario")
* #ORM\JoinTable(name="rol_funcionalidad")
*/
private $funcionalidades;
/**
* #ORM\ManyToMany(targetEntity="Usuario", mappedBy="rolesUsuario")
*/
private $usuarios;
public function getAttributes()
{
return get_class_vars(__CLASS__);
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
*
* #return Rol
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set descripcion
*
* #param string $descripcion
*
* #return Rol
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* #return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* #return string
*/
public function __toString()
{
return $this->getNombre();
}
/**
* Constructor
*/
public function __construct()
{
$this->funcionalidades = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuarios = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add funcionalidade
*
* #param \CECMED\SeguridadBundle\Entity\Rol $funcionalidade
*
* #return Rol
*/
public function addFuncionalidade(\CECMED\SeguridadBundle\Entity\Rol $funcionalidade)
{
$this->funcionalidades[] = $funcionalidade;
return $this;
}
/**
* Remove funcionalidade
*
* #param \CECMED\SeguridadBundle\Entity\Rol $funcionalidade
*/
public function removeFuncionalidade(\CECMED\SeguridadBundle\Entity\Rol $funcionalidade)
{
$this->funcionalidades->removeElement($funcionalidade);
}
/**
* Get funcionalidades
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFuncionalidades()
{
return $this->funcionalidades;
}
/**
* Add usuario
*
* #param \CECMED\SeguridadBundle\Entity\Usuario $usuario
*
* #return Rol
*/
public function addUsuario(\CECMED\SeguridadBundle\Entity\Usuario $usuario)
{
$usuario->addRolesUsuario($this);
$this->usuarios[] = $usuario;
return $this;
}
/**
* Remove usuario
*
* #param \CECMED\SeguridadBundle\Entity\Usuario $usuario
*/
public function removeUsuario(\CECMED\SeguridadBundle\Entity\Usuario $usuario)
{
$this->usuarios->removeElement($usuario);
}
/**
* Get usuarios
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsuarios()
{
return $this->usuarios;
}
}
This is the Usuario Class
class Usuario implements AdvancedUserInterface
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="estado", type="boolean")
*/
private $estado;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #ORM\ManyToMany(targetEntity="Rol", inversedBy="usuarios")
* #ORM\JoinTable(name="usuario_rol")
*/
private $rolesUsuario;
/**
* #ORM\OneToOne(targetEntity="Persona")
* #ORM\JoinColumn(name="persona_id", referencedColumnName="id")
*/
private $persona;
public function getAttributes()
{
return get_class_vars(__CLASS__);
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return Usuario
*/
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 Usuario
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set estado
*
* #param string $estado
*
* #return Usuario
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* #return string
*/
public function getEstado()
{
return $this->estado;
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
return true;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
return true;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return true;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
if($this->estado == true){
return true;
}else{
return false;
}
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRolesUsuario()
{
return $this->rolesUsuario;
}
public function getRoles()
{
$r = array();
foreach ($this->rolesUsuario as $roles){
$r[] = $roles->getNombre();
}
return $r;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
return $this->salt;
}
/**
* 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 false;
}
/**
* Constructor
*/
public function __construct()
{
$this->rolesUsuario = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set salt
*
* #param string $salt
*
* #return Usuario
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Add role
*
* #param \CECMED\SeguridadBundle\Entity\Rol $role
*
* #return Usuario
*/
public function addRole(\CECMED\SeguridadBundle\Entity\Rol $role)
{
$this->rolesUsuario[] = $role;
return $this;
}
/**
* Remove role
*
* #param \CECMED\SeguridadBundle\Entity\Rol $role
*/
public function removeRole(\CECMED\SeguridadBundle\Entity\Rol $role)
{
$this->rolesUsuario->removeElement($role);
}
/**
* Set persona
*
* #param \CECMED\SeguridadBundle\Entity\persona $persona
*
* #return Usuario
*/
public function setPersona(\CECMED\SeguridadBundle\Entity\persona $persona = null)
{
$this->persona = $persona;
return $this;
}
/**
* Get persona
*
* #return \CECMED\SeguridadBundle\Entity\persona
*/
public function getPersona()
{
return $this->persona;
}
/**
* #return string
*/
public function __toString()
{
return $this->getUsername();
}
/**
* Add rolesUsuario
*
* #param \CECMED\SeguridadBundle\Entity\Rol $rolesUsuario
*
* #return Usuario
*/
public function addRolesUsuario(\CECMED\SeguridadBundle\Entity\Rol $rolesUsuario)
{
$this->rolesUsuario[] = $rolesUsuario;
return $this;
}
/**
* Remove rolesUsuario
*
* #param \CECMED\SeguridadBundle\Entity\Rol $rolesUsuario
*/
public function removeRolesUsuario(\CECMED\SeguridadBundle\Entity\Rol $rolesUsuario)
{
$this->rolesUsuario->removeElement($rolesUsuario);
}
}
The Problem is that, when i generate schema with cli and the CRUD,The Usuario form works fine and it registers the role in database, but the Rol form when I insert a record does not register the user in database

What I have found with my foreign keys in Symfony is #ORM\JoinColumn was redundant. Doctrine can find the column from the #ORM\ManyToMany on its own. It's not clear in the docs in my opinion. I have not tried this with Many to Many relationships, but I have done quite a few Many to Ones. I had several issues until I just deleted all the JoinColumns. Try it out. Let me know how it goes.

Related

Retrieve user from existing table User

I'm really new to Symfony and I'm learning how it works.
So I have a DB and a table on it called USER with the fields name,username,password etc etc.
I'm trying to create a login form that will take the user from that table.
I've already created my enity User
I've read the doc here, but it's not what I want, because as i said my entity it's still there.
Should I use FOS user bunble? I've read the doc here of this bundle, but I didn't get the final part (step7).So my question is, can I use my User Entity with FOS user Bundle? If the answer is no, there is another solution to that, sicne I don't what to change my DB table?
Thank everyone in advance
P.s I generated the User entity following this dochere and this is the resulting class
namespace LocalWorker\BackendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Utente
*/
class Utente
{
/**
* #var string
*/
private $uNome;
/**
* #var string
*/
private $uCognome;
/**
* #var string
*/
private $uUsername;
/**
* #var string
*/
private $uPassword;
/**
* #var string
*/
private $uEmail;
/**
* #var string
*/
private $uRuolo;
/**
* #var integer
*/
private $uStatus;
/**
* #var \DateTime
*/
private $uDateIns;
/**
* #var \DateTime
*/
private $uDateActive;
/**
* #var integer
*/
private $uId;
/**
* Set uNome
*
* #param string $uNome
* #return Utente
*/
public function setUNome($uNome)
{
$this->uNome = $uNome;
return $this;
}
/**
* Get uNome
*
* #return string
*/
public function getUNome()
{
return $this->uNome;
}
/**
* Set uCognome
*
* #param string $uCognome
* #return Utente
*/
public function setUCognome($uCognome)
{
$this->uCognome = $uCognome;
return $this;
}
/**
* Get uCognome
*
* #return string
*/
public function getUCognome()
{
return $this->uCognome;
}
/**
* Set uUsername
*
* #param string $uUsername
* #return Utente
*/
public function setUUsername($uUsername)
{
$this->uUsername = $uUsername;
return $this;
}
/**
* Get uUsername
*
* #return string
*/
public function getUUsername()
{
return $this->uUsername;
}
/**
* Set uPassword
*
* #param string $uPassword
* #return Utente
*/
public function setUPassword($uPassword)
{
$this->uPassword = $uPassword;
return $this;
}
/**
* Get uPassword
*
* #return string
*/
public function getUPassword()
{
return $this->uPassword;
}
/**
* Set uEmail
*
* #param string $uEmail
* #return Utente
*/
public function setUEmail($uEmail)
{
$this->uEmail = $uEmail;
return $this;
}
/**
* Get uEmail
*
* #return string
*/
public function getUEmail()
{
return $this->uEmail;
}
/**
* Set uRuolo
*
* #param string $uRuolo
* #return Utente
*/
public function setURuolo($uRuolo)
{
$this->uRuolo = $uRuolo;
return $this;
}
/**
* Get uRuolo
*
* #return string
*/
public function getURuolo()
{
return $this->uRuolo;
}
/**
* Set uStatus
*
* #param integer $uStatus
* #return Utente
*/
public function setUStatus($uStatus)
{
$this->uStatus = $uStatus;
return $this;
}
/**
* Get uStatus
*
* #return integer
*/
public function getUStatus()
{
return $this->uStatus;
}
/**
* Set uDateIns
*
* #param \DateTime $uDateIns
* #return Utente
*/
public function setUDateIns($uDateIns)
{
$this->uDateIns = $uDateIns;
return $this;
}
/**
* Get uDateIns
*
* #return \DateTime
*/
public function getUDateIns()
{
return $this->uDateIns;
}
/**
* Set uDateActive
*
* #param \DateTime $uDateActive
* #return Utente
*/
public function setUDateActive($uDateActive)
{
$this->uDateActive = $uDateActive;
return $this;
}
/**
* Get uDateActive
*
* #return \DateTime
*/
public function getUDateActive()
{
return $this->uDateActive;
}
/**
* Get uId
*
* #return integer
*/
public function getUId()
{
return $this->uId;
}
}

Entity relationship showing "Entity not Found" when relation with two different vendor's bundle in Symfony2

I have created two bundle using two different vendor names. Two bundle names is-
SystemUsersBundle
Namespace= SystemUsersBundle\Namespace
AppBundle
Namespace= AppBundle\Namespace
Now, I have created two Entity inside two bundle. Entity name given below-
Comment.php – this entity created under AppBundle and it’s namespace
is AppBundle\Entity.
Users.php – this entity created under SystemUsersBundle and it’s
namespace is SystemUsersBundle\Entity.
My directory Structure is-
Now, I wanted to make a relationship between Users.php and Comment.php entity. For this purpose I make a relation between them according to the rule of Doctrine ManyToOne relationship.
Users.php and Comment.php file given below-
Users.php
<?php
namespace SystemUsersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Users
*
* #ORM\Table("users")
*/
class Users implements AdvancedUserInterface
{
/**
* #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=255)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #Gedmo\Slug(fields={"name"}, updatable=false)
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*/
private $plainpassword;
/**
* #var string
*/
private $resetPassword;
/**
* #var array
*
* #ORM\Column(name="roles", type="array")
*/
private $roles = array();
/**
* #var boolean
*
* #ORM\Column(name="app_status", type="boolean")
*/
private $appStatus;
/**
* #var boolean
*
* #ORM\Column(name="is_active",type="boolean")
*/
private $isActive;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
public function __construct()
{
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* 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 name
*
* #param string $name
* #return Users
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* 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 slug
*
* #param string $slug
* #return Users
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* 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 plainpassword for the application
*
* #param type $plainpassword
*/
function setPlainpassword($plainpassword)
{
$this->plainpassword = $plainpassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getPlainpassword()
{
return $this->plainpassword;
}
/**
* Set resetPassword for the application
*
* #param type $resetPassword
*/
function setResetPassword($resetPassword)
{
$this->resetPassword = $resetPassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getResetPassword()
{
return $this->resetPassword;
}
/**
* Set roles
*
* #param string $roles
* #return Users
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return string
*/
public function getRoles()
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
/**
* set salt property of user
*
* #return type
*/
function getSalt()
{
return $this->salt;
}
/**
* Get salt value of user
*
* #param type $salt
*/
function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Set appStatus
*
* #param boolean $appStatus
* #return Users
*/
public function setAppStatus($appStatus)
{
$this->appStatus = $appStatus;
return $this;
}
/**
* Get appStatus
*
* #return boolean
*/
public function getAppStatus()
{
return $this->appStatus;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Users
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Users
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get Is active property
*
* #return type
*/
function getIsActive()
{
return $this->isActive;
}
/**
* Set Is active property
*
* #param \SystemUsersBundle\Entity\type $isActive
* #return $users
*/
function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* erase plain password credentials
*/
public function eraseCredentials()
{
$this->setPlainpassword(null);
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
return true;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
return true;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return true;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
return $this->getIsActive();
}
Comment.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SystemUsersBundle\Entity\Users;
/**
* Comment
*
* #ORM\Table("comment")
* #ORM\Entity
*/
class Comment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var integer
*
* #ORM\Column(name="user_id", type="integer")
*/
private $userId;
/**
* #var boolean
*
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Comment
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set userId
*
* #param integer $userId
* #return Comment
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set status
*
* #param boolean $status
* #return Comment
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
}
In comment.php file, make relationship using
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
it's give the following error-
But if I wanted make relationship with two entity under same Bundle(like SystemUsersBundle or AppBundle) it works perfectly ok. If you need more information let me know.
The provided syntax #ORM\ManyToOne(targetEntity="Users") means that given entity is at the same namespace as of the current file. Which is not the case. Your mapping should be like this:
#ORM\ManyToOne(targetEntity="SystemUsersBundle\Entity\Users")
When entities are in different namespace, you should always provide the full path.
If you need to set a relation between your two entities just make it all in one bundle, why you use two bundle if they depends on each other.
take a look at this :
A bundle is meant to be something that can be reused as a stand-alone piece of software. If UserBundle cannot be used "as is" in other Symfony apps, then it shouldn't be its own bundle. Moreover, if InvoiceBundle depends on ProductBundle, then there's no advantage to having two separate bundles.

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

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

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

Symfony2 - a User references a roles entity by id but i can't retrieve the user rol when i log in

This is my user entity
<?php
namespace Monse\UsuariosBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\UsuariosBundle\Entity\Usuario
*
* #ORM\Table(name="users")
* #ORM\Entity
*/
class Usuario implements UserInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Monse\ClientesBundle\Entity\Cliente")
* #ORM\JoinColumn(name="cliente_id", referencedColumnName="id",nullable=true)
*/
protected $cliente;
/**
* #var string $usuario
*
* #ORM\Column(name="usuario", type="string", length=255, unique=true)
*/
protected $usuario;
/**
* #var string $email
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
protected $email;
/**
* #var string $password
*
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #var string $salt
*
* #ORM\Column(name="salt", type="string", length=255)
*/
protected $salt;
/**
* #var date $ultimo_ingreso
*
* #ORM\Column(name="ultimo_ingreso", type="date")
*/
protected $ultimo_ingreso;
/**
* #var date $fecha_alta
*
* #ORM\Column(name="fecha_alta", type="date")
*/
protected $fecha_alta;
/**
* #ORM\ManyToOne(targetEntity="Monse\UsuariosBundle\Entity\Rol")
* #ORM\JoinColumn(name="rol", referencedColumnName="id",nullable=false)
*/
protected $rol;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function setCliente(\Monse\ClientesBundle\Entity\Cliente $cliente)
{
$this->cliente = $cliente;
}
/**
* Get cliente
*
* #return integer
*/
public function getCliente()
{
return $this->cliente;
}
/**
* Set usuario
*
* #param string $usuario
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set email
*
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set contrasena
*
* #param string $contrasena
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get contrasena
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set salt
*
* #param string $salt
*/
public function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set ultimo_ingreso
*
* #param date $ultimoIngreso
*/
public function setUltimoIngreso($ultimoIngreso)
{
$this->ultimo_ingreso = $ultimoIngreso;
}
/**
* Get ultimo_ingreso
*
* #return date
*/
public function getUltimoIngreso()
{
return $this->ultimo_ingreso;
}
/**
* Set fecha_alta
*
* #param date $fechaAlta
*/
public function setFechaAlta($fechaAlta)
{
$this->fecha_alta = $fechaAlta;
}
/**
* Get fecha_alta
*
* #return date
*/
public function getFechaAlta()
{
return $this->fecha_alta;
}
/**
* Set rol
*
* #param integer $rol
*/
public function setRol(\Monse\UsuariosBundle\Entity\Rol $rol)
{
$this->rol = $rol;
}
/**
* Get rol
*
* #return integer
*/
public function getRol()
{
return $this->rol;
}
public function __construct()
{
$this->fecha_alta = new \DateTime();
}
function equals(\Symfony\Component\Security\Core\User\UserInterface $usuario)
{
return $this->getUsuario() == $usuario->getUsername();
}
function eraseCredentials()
{
}
function getRoles()
{
}
function getUsername()
{
return $this->getUsuario();
}
}
and this is my roles entity
<?php
namespace Monse\UsuariosBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\UsuariosBundle\Entity\Rol
*
* #ORM\Table(name="roles")
* #ORM\Entity
*/
class Rol implements RoleInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $role
*
* #ORM\Column(name="rol", type="string", length=255)
*/
protected $role;
/**
* #var string $denominacion
*
* #ORM\Column(name="denominacion", type="string", length=255)
*/
protected $denominacion;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set rol
*
* #param string $rol
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* Get rol
*
* #return string
*/
public function getRole()
{
return $this->role;
}
public function setDenominacion($denominacion)
{
$this->denominacion = $denominacion;
}
/**
* Get denominacion
*
* #return string
*/
public function getDenominacion()
{
return $this->denominacion;
}
public function __toString() {
return $this->denominacion;
}
}
Please HELP, i don't know what i'm doing wrong?
I need to administrate ROLES, that's why i have the entity.
In the Rol entity
rol has ROLE_ADMIN, ROLE_USER...
denominacion is Super Admin, Admin, User, etc...
I need to retreive ROL
Function getRoles() in Usuario should return an array of role names. Why yours is empty?
public function getRoles()
{
return $this->roles->map(function($r) { return $r->getRole(); })
->toArray();
}
Usuario has a many to one relation with role. Are you sure this is correct? The above example assumes that you have a collection of roles.

Categories