I'm creating a multi step form in Symfony 3.3 where I save the form data each step to a session. The entity of the form also has the user as form property. When the user is added to the entity, all data is saved correctly to the session. But when I submit the form and then load the data from session again, most of the data of the user (as form property of entity) is gone. Only the username, id, passwordEncoded is in session, all other variables of the user (firstName, lastName, email, ...) is NULL. It is the same when I save only the user to the session. Is there something which I have to do after saving the user to session? Why is the data of the user lost after reloading the page?
Thanks and best!
Entity\User:
class User extends EntitySuperclass implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\Column(type="string")
*/
private $username;
/**
*
* #Assert\Length(max=4096,groups={"account_complete","account_password","user"})
* #Assert\Length(min = 8,groups={"account_complete","account_password","user"}, minMessage="user.password_length")
*/
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)
* #Assert\NotBlank(groups={"account_register","user"})
* #Assert\Email(
* groups = {"account_register", "account","user"},
* strict = true,
* checkMX = true
* )
*/
private $email;
/**
* #ORM\Column(type="string", length=255)
*/
private $emailNew = '';
/**
* #ORM\ManyToOne(targetEntity="Salutation")
*
*/
private $salutation;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(groups={"account_complete","user"})
* #Assert\Regex(pattern = "/^[a-zA-ZäöüÄÖÜß0-9 ]+$/",groups={"account_complete","user"}, message="user.first_name.regex")
*/
private $firstName;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(groups={"account_complete","user"})
* #Assert\Regex(pattern = "/^[a-zA-ZäöüÄÖÜß0-9 ]+$/",groups={"account_complete","user"}, message="user.last_name.regex")
*/
private $lastName;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive = false;
/**
* #ORM\Column(name="email_confirmed", type="boolean")
*/
private $emailConfirmed = false;
/**
* #ORM\Column(type="integer")
*/
private $shibbolethState = 0;
/**
* #ORM\Column(type="string")
*/
private $shibbolethHash = '';
/**
* #ORM\Column(type="string")
*/
private $shibbolethPersistentId = '';
/**
* #ORM\ManyToMany(targetEntity="UserGroup")
* #ORM\JoinTable(name="User_UserGroup",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
private $userGroups;
/**
* #ORM\Column(type="integer")
*/
private $confirmationEmailSend;
/**
* #ORM\Column(type="integer")
*/
private $lastLogin = 0;
/**
* #ORM\Column(type="integer")
*/
protected $expires = 0;
/**
* #ORM\Column(type="string", length=255)
*/
private $sessionId = '';
/**
* #ORM\ManyToMany(targetEntity="BankDetails", cascade={"persist"})
* #ORM\JoinTable(name="User_BankDetails",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="bank_details_id", referencedColumnName="id")}
* )
*/
private $bankDetails;
/**
* #ORM\ManyToMany(targetEntity="Address", cascade={"persist"})
* #ORM\JoinTable(name="User_BillingAddress",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="billing_address_id", referencedColumnName="id")}
* )
* #Assert\Count(
* min = 1,
* minMessage = "user.billing_addresses.min",
* )
* #Assert\Valid
*/
private $billingAddresses;
public function __construct()
{
parent::__construct();
$this->isActive = true;
$this->confirmationEmailSend = 0;
$this->userGroups = new ArrayCollection();
$this->bankDetails = new ArrayCollection();
$this->billingAddresses = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$currentTimestamp = time();
if($this->getConfirmationEmailSend() == NULL)
$this->setConfirmationEmailSend(0);
}
public function getUsername()
{
//return $this->username;
return $this->email;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
$roles = array();
$userGroups = $this->getUserGroups();
if(!empty($userGroups)) {
foreach($userGroups as $userGroup) {
$role = $userGroup->getRole();
$roles[] = 'ROLE_'.strtoupper($role);
}
}
return $roles;
}
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
public function eraseCredentials()
{
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->isActive,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->isActive,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
$this->setUsername($email);
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* 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;
}
/**
* Add userGroup
*
* #param \AppBundle\Entity\UserGroup $userGroup
*
* #return User
*/
public function addUserGroup(\AppBundle\Entity\UserGroup $userGroup)
{
$this->userGroups[] = $userGroup;
return $this;
}
/**
* Remove userGroup
*
* #param \AppBundle\Entity\UserGroup $userGroup
*/
public function removeUserGroup(\AppBundle\Entity\UserGroup $userGroup)
{
$this->userGroups->removeElement($userGroup);
}
/**
* Get userGroups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUserGroups()
{
return $this->userGroups;
}
/**
* Set shibbolethPersistentId
*
* #param string $shibbolethPersistentId
*
* #return User
*/
public function setShibbolethPersistentId($shibbolethPersistentId)
{
$this->shibbolethPersistentId = $shibbolethPersistentId;
return $this;
}
/**
* Get shibbolethPersistentId
*
* #return string
*/
public function getShibbolethPersistentId()
{
return $this->shibbolethPersistentId;
}
/**
* Set firstName
*
* #param string $firstName
*
* #return User
*/
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 User
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set emailConfirmed
*
* #param boolean $emailConfirmed
*
* #return User
*/
public function setEmailConfirmed($emailConfirmed)
{
$this->emailConfirmed = $emailConfirmed;
return $this;
}
/**
* Get emailConfirmed
*
* #return boolean
*/
public function getEmailConfirmed()
{
return $this->emailConfirmed;
}
public function removeAllUserGroups() {
$userGroups = $this->getUserGroups();
foreach($userGroups as $userGroup) {
$this->removeUserGroup($userGroup);
}
}
public function hasUserGroup($userGroupId) {
foreach($this->getUserGroups() as $userGroup) {
if($userGroup->getId() == $userGroupId)
return true;
}
return false;
}
/**
* Set lastLogin
*
* #param integer $lastLogin
*
* #return User
*/
public function setLastLogin($lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* Get lastLogin
*
* #return integer
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* Set confirmationEmailSend
*
* #param integer $confirmationEmailSend
*
* #return User
*/
public function setConfirmationEmailSend($confirmationEmailSend)
{
$this->confirmationEmailSend = $confirmationEmailSend;
return $this;
}
/**
* Get confirmationEmailSend
*
* #return integer
*/
public function getConfirmationEmailSend()
{
return $this->confirmationEmailSend;
}
/**
* Set validTill
*
* #param integer $validTill
*
* #return User
*/
public function setValidTill($validTill)
{
$this->validTill = $validTill;
return $this;
}
/**
* Get validTill
*
* #return integer
*/
public function getValidTill()
{
return $this->validTill;
}
/**
* Set shibbolethValid
*
* #param integer $shibbolethValid
*
* #return User
*/
public function setShibbolethValid($shibbolethValid)
{
$this->shibbolethValid = $shibbolethValid;
return $this;
}
/**
* Get shibbolethValid
*
* #return integer
*/
public function getShibbolethValid()
{
return $this->shibbolethValid;
}
/**
* Set shibbolethHash
*
* #param string $shibbolethHash
*
* #return User
*/
public function setShibbolethHash($shibbolethHash)
{
$this->shibbolethHash = $shibbolethHash;
return $this;
}
/**
* Get shibbolethHash
*
* #return string
*/
public function getShibbolethHash()
{
return $this->shibbolethHash;
}
/**
* Set shibbolethState
*
* #param integer $shibbolethState
*
* #return User
*/
public function setShibbolethState($shibbolethState)
{
$this->shibbolethState = $shibbolethState;
return $this;
}
/**
* Get shibbolethState
*
* #return integer
*/
public function getShibbolethState()
{
return $this->shibbolethState;
}
/**
* Set expires
*
* #param integer $expires
*
* #return User
*/
public function setExpires($expires)
{
$this->expires = $expires;
return $this;
}
/**
* Get expires
*
* #return integer
*/
public function getExpires()
{
return $this->expires;
}
/**
* Set emailNew
*
* #param string $emailNew
*
* #return User
*/
public function setEmailNew($emailNew)
{
$this->emailNew = $emailNew;
return $this;
}
/**
* Get emailNew
*
* #return string
*/
public function getEmailNew()
{
return $this->emailNew;
}
/**
* Set passwordHash
*
* #param string $passwordHash
*
* #return User
*/
public function setPasswordHash($passwordHash)
{
$this->passwordHash = $passwordHash;
return $this;
}
/**
* Get passwordHash
*
* #return string
*/
public function getPasswordHash()
{
return $this->passwordHash;
}
/**
* Set sessionId
*
* #param string $sessionId
*
* #return User
*/
public function setSessionId($sessionId)
{
$this->sessionId = $sessionId;
return $this;
}
/**
* Get sessionId
*
* #return string
*/
public function getSessionId()
{
return $this->sessionId;
}
/**
* Set salutation
*
* #param \AppBundle\Entity\Salutation $salutation
*
* #return User
*/
public function setSalutation(\AppBundle\Entity\Salutation $salutation = null)
{
$this->salutation = $salutation;
return $this;
}
/**
* Get salutation
*
* #return \AppBundle\Entity\Salutation
*/
public function getSalutation()
{
return $this->salutation;
}
/**
* Add bankDetail
*
* #param \AppBundle\Entity\BankDetails $bankDetail
*
* #return User
*/
public function addBankDetail(\AppBundle\Entity\BankDetails $bankDetail)
{
$this->bankDetails[] = $bankDetail;
return $this;
}
/**
* Remove bankDetail
*
* #param \AppBundle\Entity\BankDetails $bankDetail
*/
public function removeBankDetail(\AppBundle\Entity\BankDetails $bankDetail)
{
$this->bankDetails->removeElement($bankDetail);
}
/**
* Get bankDetails
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBankDetails()
{
return $this->bankDetails;
}
/**
* Add billingAddress
*
* #param \AppBundle\Entity\Address $billingAddress
*
* #return User
*/
public function addBillingAddress(\AppBundle\Entity\Address $billingAddress)
{
$this->billingAddresses[] = $billingAddress;
return $this;
}
/**
* Remove billingAddress
*
* #param \AppBundle\Entity\Address $billingAddress
*/
public function removeBillingAddress(\AppBundle\Entity\Address $billingAddress)
{
$this->billingAddresses->removeElement($billingAddress);
}
/**
* Set billingAddresses
*
* #param \AppBundle\Entity\Address $billingAddress
*
* #return User
*
*/
public function setBillingAddresses(\AppBundle\Entity\Address $billingAddress)
{
if($this->billingAddresses !== NULL and $this->billingAddresses->contains($billingAddress)){
return false;
}
$this->addBillingAddress($billingAddress);
return $this;
}
/**
* Set one billingAddresses
*
* #param \AppBundle\Entity\Address $billingAddress
*
* #return User
*
*/
public function setOneBillingAddresses(\AppBundle\Entity\Address $billingAddress)
{
$this->billingAddresses = $billingAddress;
return $this;
}
/**
* Set one billingAddresses
*
* #param \AppBundle\Entity\Address $billingAddress
*
* #return User
*
*/
public function unsetBillingAddresses()
{
$this->billingAddresses = new ArrayCollection();
return $this;
}
/**
* Get billingAddresses
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBillingAddresses()
{
return $this->billingAddresses;
}
}
Related
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.
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?
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;
}
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);
class Accounts extends AbstractType
{
private $em;
private $accountrepo = null;
private $choices = array();
public function __construct()
{
}
public function setAccountRepository($repo)
{
$this->accountrepo = $repo;
return $this;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'choices' => $this->getChoices(),
'attr' => [
'data-dojo-type' => 'dijit/form/FilteringSelect',
],
'data_class' => 'Far\MT\AccountBundle\Entity\Account'
]);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'Accounts';
}
public function getChoices()
{
if ( count($this->choices) > 0 ) {
return $this->choices;
}
$this->choices[0] = "";
foreach ($this->accountrepo->findAll() as $account) {
$this->choices[$account->getId()] = $account->getName() . " (" .
$account->getCurrency().") ";
}
return $this->choices;
}
}
Using the code above I get the error:
Notice: Object of class
Proxies__CG__\Far\MT\AccountBundle\Entity\Account could not be
converted to int in
/workspace/tools/vendorsymfony2/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php
line 457
This only happens when I edit the record, I'm using this Type has a ChoiceList type in order to have the db values filtered and placed on the "combobox".
Any sugestions on what I can be doing wrong?
EDIT
use Doctrine\ORM\Mapping as ORM;
/**
* Movement
*
* #ORM\Entity(repositoryClass="Far\MT\AccountBundle\Entity\MovementRepository")
* #ORM\Table(name="movement")
*/
class Movement
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Date
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="MovementType")
* #ORM\JoinColumn(name="movementtype", referencedColumnName="id", unique=false)
*/
private $Type;
/**
* #var float
*
* #ORM\Column(name="value", type="float")
*/
private $value;
/**
* #var Account
*
* #ORM\ManyToOne(targetEntity="Account", cascade={"persist"})
* #ORM\JoinColumn(name="fromaccount", referencedColumnName="id", unique=false)
*/
private $fromAccount;
/**
* #var Account
*
* #ORM\ManyToOne(targetEntity="Account", cascade={"persist"})
* #ORM\JoinColumn(name="toaccount", referencedColumnName="id", unique=false)
*/
private $toAccount;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="ExpenseType", cascade={"persist"})
* #ORM\JoinColumn(name="expensetype", referencedColumnName="id",
* nullable=true, unique=false)
*/
private $ExpenseType;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="Holder", cascade={"persist"})
* #ORM\JoinColumn(name="holder", referencedColumnName="id", unique=false)
*/
private $orderHolder;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=254)
*/
private $description;
/**
* #var float
*
* #ORM\Column(name="xrate", type="float", nullable=true)
*/
private $xrate = null;
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Account
*
* #param string $account
* #return Movement
*/
public function setAccount($account)
{
$this->Account = $account;
return $this;
}
/**
* Get Account
*
* #return string
*/
public function getAccount()
{
return $this->Account;
}
/**
* Set date
*
* #param \DateTime $date
* #return Movement
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set Type
*
* #param string $type
* #return Movement
*/
public function setType($type)
{
$this->Type = $type;
return $this;
}
/**
* Get Type
*
* #return string
*/
public function getType()
{
return $this->Type;
}
/**
* Set value
*
* #param float $value
* #return Movement
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return float
*/
public function getValue()
{
return $this->value;
}
/**
* Set fromAccount
*
* #param string $fromAccount
* #return Movement
*/
public function setFromAccount($fromAccount)
{
$this->fromAccount = $fromAccount;
return $this;
}
/**
* Get fromAccount
*
* #return string
*/
public function getFromAccount()
{
return $this->fromAccount;
}
/**
* Set toAccount
*
* #param string $toAccount
* #return Movement
*/
public function setToAccount($toAccount)
{
$this->toAccount = $toAccount;
return $this;
}
/**
* Get toAccount
*
* #return string
*/
public function getToAccount()
{
return $this->toAccount;
}
/**
* Set ExpenseType
*
* #param string $expenseType
* #return Movement
*/
public function setExpenseType($expenseType)
{
$this->ExpenseType = $expenseType;
return $this;
}
/**
* Get ExpenseType
*
* #return string
*/
public function getExpenseType()
{
return $this->ExpenseType;
}
/**
* Set orderHolder
*
* #param string $orderHolder
* #return Movement
*/
public function setOrderHolder($orderHolder)
{
$this->orderHolder = $orderHolder;
return $this;
}
/**
* Get orderHolder
*
* #return string
*/
public function getOrderHolder()
{
return $this->orderHolder;
}
/**
* Set exchange rate for movement
*
* #param float $xrate
*/
public function setXrate($xrate)
{
$this->xrate = (double)$xrate;
return $this;
}
/**
* Return movement exchange rate
*
* #return float
*/
public function getXrate()
{
return $this->xrate;
}
}
Entity Account
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Account
*
* #ORM\Table(name="account")
*
* #ORM\Entity(repositoryClass="Far\MT\AccountBundle\Entity\AccountRepository")
*/
class Account
{
public function __construct()
{
$this->holders = new ArrayCollection();
$this->pocketAccounts = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=40)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="currency", type="string", length=20)
*/
private $currency;
/**
* #var Far\MT\AccountBundle\Entity\Holder
*
* #ORM\ManyToMany(targetEntity="Holder", inversedBy="Accounts")
* #ORM\JoinTable(name="account_holder",
* joinColumns={#ORM\JoinColumn(name="account_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="holder_id",
* referencedColumnName="id")}
* )
*
*/
private $holders;
/**
* #var Far\MT\AccountBundle\Entity\Account
*
* #ORM\OneToMany(targetEntity="Account", mappedBy="parentAccount")
*/
private $pocketAccounts;
/**
*
* #ORM\ManyToOne(targetEntity="Account", inversedBy="pocketAccounts", cascade={"persist"})
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parentAccount;
/**
* Specifies the account type has string
*
* #var String
*
* #ORM\Column(name="accounttype", type="string", length=40)
*/
private $accountType;
/**
* Total value of available money this should not account money that is
* pending transaction
*
* #var double
*
* #ORM\Column(name="totalavailable", type="float")
*/
private $totalAvailable = 0;
/**
* Total value of accounted money this takes into account money that has
* pending transaction
*
* #var double
*
* #ORM\Column(name="totalaccounted", type="float")
*/
private $totalAccounted = 0;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* #param string $code
* #return Account
*/
public function setCode($code)
{
$this->code = str_replace(" ", "", strtoupper(trim($code)));
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set name
*
* #param string $name
* #return Account
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set currency
*
* #param string $currency
* #return Account
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set holders
*
* #param null|Doctrine\Common\Collections\ArrayCollection $holders
* #return Account
*/
public function setHolders($holders)
{
if ($holders === null) {
$this->holders = new ArrayCollection();
} else {
$this->holders = $holders;
}
return $this;
}
/**
* Get holders
*
* #return string
*/
public function getHolders()
{
return $this->holders;
}
/**
*
* Get Pocket accounts
*
* #return \Doctrine\Common\Collections\ArrayCollection()
*/
public function getPocketAccounts()
{
return $this->pocketAccounts;
}
public function setPocketAccounts($PocketAccounts)
{
$this->pocketAccounts = $PocketAccounts;
return $this;
}
/**
* Get Parent Account
*
* #return \Far\MT\AccountBundle\Entity\Account
*
*/
public function getParentAccount()
{
return $this->parentAccount;
}
public function setParentAccount($ParentAccount)
{
$this->parentAccount = ($ParentAccount);
return $this;
}
/**
* does this account has a parent
*
* #return boolean
*/
public function hasParentAccount()
{
return ($this->parentAccount !== null);
}
public function setAccountType($accountType)
{
$this->accountType = $accountType;
return $this;
}
public function getAccountType()
{
return $this->accountType;
}
public function getTotalAccounted()
{
return $this->totalAccounted;
}
public function setTotalAccounted($total)
{
$this->totalAccounted = $total;
return $this;
}
public function getTotalAvailable()
{
return $this->totalAvailable;
}
public function setTotalAvailable($total)
{
$this->totalAvailable = $total;
return $this;
}
public function __toString()
{
return 'Account';
}
}
Please note that what is updated is the Movement entity witch contains the Account in fromAccount and toAccount.
Not knowing the answer he pointed out to me that I did not understand the data_class parameter.
'data_class' => 'Far\MT\AccountBundle\Entity\Account'
18:37 < ocramius> netcrash: no, sorry, can't help since I don't know
what data_class does (not a sf2 form user)
I was missing a Data Transformer, data_class (specifying the Entity was working not sure the reason why...), I placed a DataTransformer and it solved the issue.
See bellow.
use Far\MT\AccountBundle\Form\DataTransformer\AccountToIdTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class Accounts extends AbstractType
{
/**
*
* #var EntityManager
*/
private $em;
private $accountrepo = null;
private $choices = array();
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$transformer = new AccountToIdTransformer($this->em);
$builder->addModelTransformer($transformer);
}
public function setAccountRepository($repo)
{
$this->accountrepo = $repo;
return $this;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'choices' => $this->getChoices(),
'attr' => [
'data-dojo-type' => 'dijit/form/FilteringSelect',
]
]);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'Accounts';
}
public function getChoices()
{
if ( count($this->choices) > 0 ) {
return $this->choices;
}
$this->choices[0] = "";
foreach ($this->accountrepo->findAll() as $account) {
$this->choices[$account->getId()] = $account->getName() . " (" .
$account->getCurrency().") ";
}
return $this->choices;
}
}
And the data transformer:
/**
* This is a transformer for the Account AbstractType
*
* #link http://symfony.com/doc/master/cookbook/form/data_transformers.html
*
* #author andref
*/
class AccountToIdTransformer implements DataTransformerInterface
{
/**
* #var ObjectManager
*/
private $om;
/**
*
* #param ObjectManager $om
*/
public function __construct($om)
{
$this->om = $om;
}
/**
* Transforms an object (issue) to a int (Id).
*
* #param Account|null $account
* #return string
*/
public function transform($account)
{
if (null === $account) {
return "";
}
return $account->getId();
}
/**
* Transforms a int (Id) to an object (Account).
*
* #param int $Id
*
* #return Account|null
*
* #throws TransformationFailedException if object (Account) is not found.
*/
public function reverseTransform($id)
{
if (!$id) {
return null;
}
$Account = $this->om
->getRepository('FarMTAccountBundle:Account')
->findOneBy(array('id' => $id))
;
if (null === $Account) {
throw new TransformationFailedException(sprintf(
'An Account with Id "%s" does not exist!',
$id
));
}
return $Account;
}
}