I have configured the FOSUserBundle Group follow Using Groups With FOSUserBundle and get it to work.
// src/SM4/UserBundle/Entity/User.php
/**
* #ORM\ManyToMany(targetEntity="SM4\UserBundle\Entity\Group")
* #ORM\JoinTable(name="sm4_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
Every time it creates a new User, I can use:
$userObj = new \SM4\UserBundle\Entity\User;
$userObj->getId();
$userObj->getEmail();
....
$userObj->getGroup();
But how do I get the Group_id of user?
Assuming you have a function as follow in your User entity:
public function getGroups()
{
return $this->groups;
}
and another one as follow in your Group entity:
public function getId()
{
return $this->id;
}
and that $this->groups is an ArrayCollection object in your User entity, you can do:
foreach ($userObj->getGroups() as $group)
{
//this is where you get your groups id
echo $group->getId();
}
Thanks cheesemacfly!... one of my ways
User Entity
namespace Hta\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** * HtaUser / class HtaUser {
/*
* #var string
*/
private $username;
/**
* #var string
*/
private $usernameCanonical;
/**
* #var string
*/
private $email;
/**
* #var string
*/
private $emailCanonical;
/**
* #var boolean
*/
private $enabled;
/**
* #var string
*/
private $salt;
/**
* #var string
*/
private $password;
/**
* #var \DateTime
*/
private $lastLogin;
/**
* #var boolean
*/
private $locked;
/**
* #var boolean
*/
private $expired;
/**
* #var \DateTime
*/
private $expiresAt;
/**
* #var string
*/
private $confirmationToken;
/**
* #var \DateTime
*/
private $passwordRequestedAt;
/**
* #var array
*/
private $roles;
/**
* #var boolean
*/
private $credentialsExpired;
/**
* #var \DateTime
*/
private $credentialsExpireAt;
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $group;
/**
* Constructor
*/
public function __construct()
{
$this->group = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set username
*
* #param string $username
* #return HtaUser
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set usernameCanonical
*
* #param string $usernameCanonical
* #return HtaUser
*/
public function setUsernameCanonical($usernameCanonical)
{
$this->usernameCanonical = $usernameCanonical;
return $this;
}
/**
* Get usernameCanonical
*
* #return string
*/
public function getUsernameCanonical()
{
return $this->usernameCanonical;
}
/**
* Set email
*
* #param string $email
* #return HtaUser
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set emailCanonical
*
* #param string $emailCanonical
* #return HtaUser
*/
public function setEmailCanonical($emailCanonical)
{
$this->emailCanonical = $emailCanonical;
return $this;
}
/**
* Get emailCanonical
*
* #return string
*/
public function getEmailCanonical()
{
return $this->emailCanonical;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return HtaUser
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set salt
*
* #param string $salt
* #return HtaUser
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set password
*
* #param string $password
* #return HtaUser
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set lastLogin
*
* #param \DateTime $lastLogin
* #return HtaUser
*/
public function setLastLogin($lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* Get lastLogin
*
* #return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* Set locked
*
* #param boolean $locked
* #return HtaUser
*/
public function setLocked($locked)
{
$this->locked = $locked;
return $this;
}
/**
* Get locked
*
* #return boolean
*/
public function getLocked()
{
return $this->locked;
}
/**
* Set expired
*
* #param boolean $expired
* #return HtaUser
*/
public function setExpired($expired)
{
$this->expired = $expired;
return $this;
}
/**
* Get expired
*
* #return boolean
*/
public function getExpired()
{
return $this->expired;
}
/**
* Set expiresAt
*
* #param \DateTime $expiresAt
* #return HtaUser
*/
public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt;
return $this;
}
/**
* Get expiresAt
*
* #return \DateTime
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Set confirmationToken
*
* #param string $confirmationToken
* #return HtaUser
*/
public function setConfirmationToken($confirmationToken)
{
$this->confirmationToken = $confirmationToken;
return $this;
}
/**
* Get confirmationToken
*
* #return string
*/
public function getConfirmationToken()
{
return $this->confirmationToken;
}
/**
* Set passwordRequestedAt
*
* #param \DateTime $passwordRequestedAt
* #return HtaUser
*/
public function setPasswordRequestedAt($passwordRequestedAt)
{
$this->passwordRequestedAt = $passwordRequestedAt;
return $this;
}
/**
* Get passwordRequestedAt
*
* #return \DateTime
*/
public function getPasswordRequestedAt()
{
return $this->passwordRequestedAt;
}
/**
* Set roles
*
* #param array $roles
* #return HtaUser
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return $this->roles;
}
/**
* Set credentialsExpired
*
* #param boolean $credentialsExpired
* #return HtaUser
*/
public function setCredentialsExpired($credentialsExpired)
{
$this->credentialsExpired = $credentialsExpired;
return $this;
}
/**
* Get credentialsExpired
*
* #return boolean
*/
public function getCredentialsExpired()
{
return $this->credentialsExpired;
}
/**
* Set credentialsExpireAt
*
* #param \DateTime $credentialsExpireAt
* #return HtaUser
*/
public function setCredentialsExpireAt($credentialsExpireAt)
{
$this->credentialsExpireAt = $credentialsExpireAt;
return $this;
}
/**
* Get credentialsExpireAt
*
* #return \DateTime
*/
public function getCredentialsExpireAt()
{
return $this->credentialsExpireAt;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add group
*
* #param \Hta\CoreBundle\Entity\HtaGroup $group
* #return HtaUser
*/
public function addGroup(\Hta\CoreBundle\Entity\HtaGroup $group)
{
$this->group[] = $group;
return $this;
}
/**
* Remove group
*
* #param \Hta\CoreBundle\Entity\HtaGroup $group
*/
public function removeGroup(\Hta\CoreBundle\Entity\HtaGroup $group)
{
$this->group->removeElement($group);
}
/**
* Get group
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroup()
{
return $this->group;
} }
Group entity
namespace Hta\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** * HtaGroup / class HtaGroup {
/*
* #var string
*/
private $name;
/**
* #var array
*/
private $roles;
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $user;
/**
* Constructor
*/
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set name
*
* #param string $name
* #return HtaGroup
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set roles
*
* #param array $roles
* #return HtaGroup
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return $this->roles;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add user
*
* #param \Hta\CoreBundle\Entity\HtaUser $user
* #return HtaGroup
*/
public function addUser(\Hta\CoreBundle\Entity\HtaUser $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \Hta\CoreBundle\Entity\HtaUser $user
*/
public function removeUser(\Hta\CoreBundle\Entity\HtaUser $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
} }
$user = $em -> getRepository('HtaCoreBundle:HtaUser' ) -> find($id);
foreach ($user->getGroup() as $group)
{
//this is where you get your groups id
echo $group->getId();
}
Notice: unserialize(): Error at offset 0 of 5 bytes in D:\symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php line 48
print_r $user object
[owner:Doctrine\ORM\PersistentCollection:private] => Hta\CoreBundle\Entity\HtaUser Object
(
[username:Hta\CoreBundle\Entity\HtaUser:private] => admin
[usernameCanonical:Hta\CoreBundle\Entity\HtaUser:private] => admin
[email:Hta\CoreBundle\Entity\HtaUser:private] => admin#yahoo.com
[emailCanonical:Hta\CoreBundle\Entity\HtaUser:private] => admin#yahoo.com
[enabled:Hta\CoreBundle\Entity\HtaUser:private] => 1
[salt:Hta\CoreBundle\Entity\HtaUser:private] =>
[password:Hta\CoreBundle\Entity\HtaUser:private] =>
[lastLogin:Hta\CoreBundle\Entity\HtaUser:private] =>
[locked:Hta\CoreBundle\Entity\HtaUser:private] =>
[expired:Hta\CoreBundle\Entity\HtaUser:private] =>
[expiresAt:Hta\CoreBundle\Entity\HtaUser:private] =>
[confirmationToken:Hta\CoreBundle\Entity\HtaUser:private] =>
[passwordRequestedAt:Hta\CoreBundle\Entity\HtaUser:private] =>
[roles:Hta\CoreBundle\Entity\HtaUser:private] => Array
(
[0] => ROLE_ADMIN
)
[credentialsExpired:Hta\CoreBundle\Entity\HtaUser:private] =>
[credentialsExpireAt:Hta\CoreBundle\Entity\HtaUser:private] =>
[id:Hta\CoreBundle\Entity\HtaUser:private] => 2
[group:Hta\CoreBundle\Entity\HtaUser:private] => Doctrine\ORM\PersistentCollection Object
RECURSION
)
how to print joined tables output? ([group:Hta\CoreBundle\Entity\HtaUser:private] => Doctrine\ORM\PersistentCollection Object
RECURSION
)
Related
I am having a problem with symfony Authentication, the point is, when i create a user, i send a email notification with a token, then when the user click on the link is when his account is activate and i do some verification like the token is correct, the user exist the account is active etc, and after that is when i am having my problem, everything is correctly until the user click on his link i do every verification but when i logged the user automatically and redirect the user to homepage the browser say that is redirecting a lot return $this->redirect($this->generateUrl('homepage'));
well there is when i am having a problem, here is my code on the securityController in activateUserAction is when i am having the problem, i hope someone can helpme
User entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User implements AdvancedUserInterface,\Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* checkMX = true
* )
*
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #Assert\NotBlank(groups={"register"})
* #Assert\Length(min = 6)
*/
private $passwordClear;
/**
* #var bool
*
* #ORM\Column(name="active", type="boolean")
*/
private $active;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #ORM\Column(name="expired", type="boolean")
*/
private $expired;
/**
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Person",cascade={"persist"})
*/
private $person;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* 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;
}
/**
* get PasswordClear
*/
public function getPasswordClear(){
return $this->passwordClear;
}
/**
* set passwordClear
*/
public function setPasswordClear($password){
$this->passwordClear=$password;
}
/**
* Set active
*
* #param boolean $active
*
* #return User
*/
public function setActive($active=0)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return bool
*/
public function getActive()
{
return $this->active;
}
/**
* Set roles
*
* #param array $roles
*
* #return User
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return array($this->roles);
}
/**
* Set person
*
* #param \AppBundle\Entity\Person $person
*
* #return User
*/
public function setPerson(\AppBundle\Entity\Person $person = null)
{
$this->person = $person;
return $this;
}
/**
* Get person
*
* #return \AppBundle\Entity\Person
*/
public function getPerson()
{
return $this->person;
}
public function getUsername()
{
return $this->getEmail();
}
public function eraseCredentials()
{
$this->passwordClear = null;
}
public function getSalt()
{
return null;
}
public function isAccountNonExpired(){
return true;
}
public function isAccountNonLocked(){
return true;
}
public function isCredentialsNonExpired(){
return true;
}
public function isEnabled(){
return $this->active;
}
/**
* Set expired
*
* #param boolean $expired
*
* #return User
*/
public function setExpired($expired)
{
$this->expired = $expired;
return $this;
}
/**
* Get expired
*
* #return boolean
*/
public function getExpired()
{
return $this->expired;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->password,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->email,
$this->password,
) = unserialize($serialized);
}
}
Entity Person
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Kernel;
/**
* Person
*
* #ORM\Table(name="person")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PersonRepository")
*/
class Person
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=255)
*/
private $lastName;
/**
* #var string
* #ORM\Column(name="desccription",type="string", length=255,nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="token", type="string", length=255)
*/
private $token;
/**
* #var string
*
* #ORM\Column(name="url_validate", type="string", length=255)
*/
private $urlValidate;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set lastName
*
* #param string $lastName
*
* #return Person
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set token
*
* #param string $token
*
* #return Person
*/
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* Get token
*
* #return string
*/
public function getToken()
{
return $this->token;
}
/**
* Set urlValidate
*
* #param string $urlValidate
*
* #return Person
*/
public function setUrlValidate($urlValidate)
{
$this->urlValidate = $urlValidate;
return $this;
}
/**
* Get urlValidate
*
* #return string
*/
public function getUrlValidate()
{
return $this->urlValidate;
}
}
My securityController
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security
\Core\Authentication\Token \UsernamePasswordToken;
use Symfony\Component\Security
\Http\Firewall\ListenerInterface;
use Symfony\Component\Security
\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security
\Core\Authentication\Token\Storage\TokenStorageInterface;
use AppBundle\Form\RegisterType;
use AppBundle\Entity\Register;
class SecurityController extends Controller
{
/**
* #Route("/login", name="user_login")
*/
public function loginAction()
{
if($this->getUser()){
return $this->redirectToRoute('homepage');
}
$authUtils = $this->get('security.authentication_utils');
return $this->render('front/homepage/_singin.html.twig', array(
'last_username' => $authUtils->getLastUsername(),
'error' => $authUtils->getLastAuthenticationError(),
));
}
/**
* #Route("/login_check", name="user_login_check")
*/
public function loginCheckAction()
{
}
/**
* #Route("/logout", name="user_logout")
*/
public function logoutAction()
{
}
/**
*
* #Route("/token/{token}", name="activate")
*/
public function activateUserAction($token){
$em = $this->getDoctrine()->getManager();
$person=$em->getRepository('AppBundle:Person')->findByToken($token);
if($person){
$user=$em->getRepository('AppBundle:User')->findByPerson($person);
$user->setActive(1);
$person->setToken("");
$person->setActivatedDate(new \DateTime());
$em->persist($person);
$em->flush();
$em->persist($user);
$em->flush();
$token= new UsernamePasswordToken(
$user,
$user->getPassword(),
'user',
$user->getRoles()
);
$this->get('security.token_storage')->setToken($token);
return $this->redirect($this->generateUrl('homepage'));
}else{
return $this->redirect($this->generateUrl('caducada'));
}
}
I'm using easyadmin and fosuserbundle.
The problém that everytime i try to update(change) the user password , nothing is happen , the same old password still the same. I think maybe i miss some config .
Config.yml
easyadmin:
Admin:
class: AppBundle\Entity\User
form:
fields:
- username
- email
- { property: 'plainPassword' , type: 'text'}
User.php:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\Util\SecureRandom;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
/**
* #Vich\Uploadable
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="user")
*
* #UniqueEntity("email")
*
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
*/
public $nom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $prenom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $adresse;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
* #Assert\Range(
* min = 00000000,
* max = 99999999,minMessage="Entrer un numero de cin correct svp",maxMessage="Entrer un numero tel correct svp"
* )
*/
protected $phone;
/**
* #var Devise[]
*
* #ORM\OneToMany(targetEntity="Devise", mappedBy="buyer")
*/
private $purchases;
/**
* The creation date of the product.
*
* #var \DateTime
* #ORM\Column(type="datetime", name="created_at")
*/
private $createdAt = null;
public function __construct()
{
parent::__construct();
// your own logic
$this->purchases = new ArrayCollection();
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set referance
*
* #param string $referance
*
*/
public function setReferance($referance )
{if($this->referance==NULL) $referance ='2';
$this->referance = $referance ;
return $this;
}
/**
* Get referance
*
* #return string
*/
public function getReferance ()
{
return $this->referance ;
}
/**
* Set forename
*
* #param string $forname
* #return User
*/
public function setForename($forename)
{
$this->forname = $forename;
return $this;
}
/**
* Get forename
*
* #return string
*/
public function getForename()
{
return $this->forname;
}
/**
* Asks whether the user is granted a particular role
*
* #return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Set nickname
*
* #param string $nickname
* #return User
*/
public function setNickname($nickname)
{
$this->nickname = $nickname;
return $this;
}
/**
* Get nickname
*
* #return string
*/
public function getNickname()
{
return $this->nickname;
}
/**
* Set lastEdited
*
* #param \DateTime $lastEdited
* #return User
*/
public function setLastEdited($lastEdited)
{
$this->lastEdited = $lastEdited;
return $this;
}
/**
* Get lastEdited
*
* #return \DateTime
*/
public function getLastEdited()
{
return $this->lastEdited;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function setLastEditedValueAsNow() {
$this->setLastEdited(new \DateTime());
}
/**
* Set surname
*
* #param string $surname
* #return User
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Utilisateurs
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function __toString()
{if ($this->prenom != null && $this->nom!= null && $this->phone != null) {
return 'prenom&nom :'.$this->prenom.' '.$this->nom.' | phone : '.$this->phone ;
}
else return 'id :'.$this->id.' | username : '.$this->username ; }
/**
* Set nom
*
* #param string $nom
*
* #return Utilisateurs
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return Utilisateurs
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set ville
*
* #param string $ville
*
* #return Utilisateurs
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set class
*
* #param string $class
*
* #return Utilisateurs
*/
public function setClass($class)
{
$this->class = $class;
return $this;
}
/**
* Get class
*
* #return string
*/
public function getClass()
{
return $this->class;
}
/**
* Set phone
*
* #param string $phone
*
* #return Utilisateurs
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Add purchase
*
* #param \AppBundle\Entity\Devise $purchase
*
* #return User
*/
public function addPurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases[] = $purchase;
return $this;
}
/**
* Remove purchase
*
* #param \AppBundle\Entity\Devise $purchase
*/
public function removePurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases->removeElement($purchase);
}
/**
* Get purchases
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPurchases()
{
return $this->purchases;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return User
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
));
}
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password) = unserialize($serialized);
}
}
I trying make relation in symphony through this http://symfony.com/doc/current/doctrine/associations.html
problemm is that when i get post and wont get related entitie (rss) i get null
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $title;
/**
* #var string
*/
private $text;
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="posts")
* #ORM\JoinColumn(name="link", referencedColumnName="id")
*/
private $rss;
/**
* #var \DateTime
*/
private $createdAt;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
*
* #return Post
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set link
*
* #param string $link
*
* #return Post
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Post
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #var integer
*/
private $user_id;
/**
* Set userId
*
* #param integer $userId
*
* #return Post
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* #var integer
*/
private $link;
public function setRss($rss){
$this->rss = $rss;
}
public function getRss(){
return $this->rss;
}
}
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* rss
*
* #ORM\Entity
* #ORM\Table(name="rss")
*/
class Rss
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $address;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return rss
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
*
* #return rss
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* #var \DateTime
*/
private $lastUpdate;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="Rss")
*/
private $posts;
public function __construct()
{
$this->posts = new ArrayCollection();
}
public function getPosts(){
return $this->posts;
}
public function setPosts($posts){
$this->posts[] = $posts;
}
/**
* Set lastUpdate
*
* #param \DateTime $lastUpdate
*
* #return rss
*/
public function setLastUpdate($lastUpdate)
{
$this->lastUpdate = $lastUpdate;
return $this;
}
/**
* Get lastUpdate
*
* #return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* #var string
*/
private $pageaddress;
/**
* Set pageaddress
*
* #param string $pageaddress
*
* #return rss
*/
public function setPageaddress($pageaddress)
{
$this->pageaddress = $pageaddress;
return $this;
}
/**
* Get pageaddress
*
* #return string
*/
public function getPageaddress()
{
return $this->pageaddress;
}
}
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('AppBundle:Post')->findAll();
$post = $this->getDoctrine()
->getRepository('AppBundle:Post')
->find(1);
$post->getRss();
This can help you:
https://knpuniversity.com/screencast/doctrine-relations/many-to-one-relation
also you can try modifying the variable $id
private $id
for
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
To create a primary key.
Entity
class Post
/**
* #ORM\ManyToOne(targetEntity="Rss", inversedBy="post")
* #ORM\JoinColumn(nullable=false)
*/
private $rss;
class Rss
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="rss")
* #ORM\OrderBy({"createdAt"="DESC"})
*/
private $post;
and the class Post you will need to create a constructor like this
public function __construct()
{
$this->posts = new ArrayCollection();
}
/**
* #return ArrayCollection|GenusNote[]
*/
public function getPosts()
{
return $this->notes;
}
I hope it can help you
I try to setup a User creation form with FOS. There, the user specific language can be choosed from a databasetable (language).
This seems to be a bad solution for the reason that there must be an other way to give a choice between four langueges on user creation form. I'm stucking, and as far as I understand the documentation, theyre talking about website translation (this is my second step but first I need to setup the users).
Is there a nice way to get hteese languages into the creation form: actually, my form looks like
$form = $this->createFormBuilder($user)
->add('firstname', 'text')
->add('usergroups', 'entity', array('class' => 'PrUserBundle:Group','property' => 'name'))
->add('language', 'entity', array('class' => 'PrUserBundle:Language','property' => 'name'))
->add('lastname', 'text')
->add('username', 'text')
->add('email', 'text')
->add('phone', 'text')
->add('password', 'password')
->add('save', 'submit')
->getForm();
It works but with
->add('language', 'entity', array('class' => 'PrUserBundle:Language','property' => 'name'))
Cause an error for the reason that there are no getters and setters for it in my user class.
My User Class also don't know about the language so adding getters will bring no result :(
My User Entity:
<?php
// src/Pr/UserBundle/Entity/User.php
namespace Pr\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="sys_user")
*/
class User extends BaseUser
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $client;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $client_id;
/**
* #ORM\Column(type="string", length=16383, nullable=true) //16383 = max varchar utf8
*/
private $imageurl;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $firstname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $lastname;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $phone;
/**
* #ORM\Column(type="integer", nullable = true)
*/
protected $lock_state;
/**
* #ORM\Column(type="array", nullable=true)
*/
private $locations;
/**
* #ORM\Column(type="array", nullable=true)
*/
private $usergroups;
/**
* #ORM\Column(type="string", length=5, options={"fixed" = true, "default" = "de_DE"})
*/
private $locale = 'de_DE';
/**
* #ORM\Column(type="string", length=32)
*/
private $timezone = 'UTC';
/**
* #ORM\Column(type="array", nullable=true)
*/
private $created='1';
//do not persist!
protected $plain_password;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set client
*
* #param integer $client
* #return User
*/
public function setClient($client)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* #return integer
*/
public function getClient()
{
return $this->client;
}
/**
* Set client_id
*
* #param integer $clientId
* #return User
*/
public function setClientId($clientId)
{
$this->client_id = $clientId;
return $this;
}
/**
* Get client_id
*
* #return integer
*/
public function getClientId()
{
return $this->client_id;
}
/**
* Set imageurl
*
* #param string $imageurl
* #return User
*/
public function setImageurl($imageurl)
{
$this->imageurl = $imageurl;
return $this;
}
/**
* Get imageurl
*
* #return string
*/
public function getImageurl()
{
return $this->imageurl;
}
/**
* 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 phone
*
* #param string $phone
* #return User
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set lock_state
*
* #param integer $lockState
* #return User
*/
public function setLockState($lockState)
{
$this->lock_state = $lockState;
return $this;
}
/**
* Get lock_state
*
* #return integer
*/
public function getLockState()
{
return $this->lock_state;
}
/**
* Set locations
*
* #param array $locations
* #return User
*/
public function setLocations($locations)
{
$this->locations = $locations;
return $this;
}
/**
* Get locations
*
* #return array
*/
public function getLanguage()
{
return $this->language;
}
/**
* Get locations
*
* #return array
*/
public function getLocations()
{
return $this->locations;
}
/**
* Set usergroups
*
* #param array $usergroups
* #return User
*/
public function setUsergroups($usergroups)
{
$this->usergroups = $usergroups;
return $this;
}
/**
* Get usergroups
*
* #return array
*/
public function getUsergroups()
{
return $this->usergroups;
}
/**
* Set locale
*
* #param string $locale
* #return User
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Get locale
*
* #return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* Set timezone
*
* #param string $timezone
* #return User
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone;
return $this;
}
/**
* Get timezone
*
* #return string
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* Set created
*
* #param array $created
* #return User
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return array
*/
public function getCreated()
{
return $this->created;
}
}
Reading this page I've setup a form to handle PATCH requests.
I've a Player entity:
<?php
namespace Acme\PlayerBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\PlayerBundle\Entity\Player
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\PlayerBundle\Entity\PlayerRepository")
*/
class Player
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #ORM\ManyToOne(targetEntity="Acme\TeamBundle\Entity\Team", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotBlank()
*/
private $team;
/**
* #var integer $shirtNumber
*
* #ORM\Column(name="shirtNumber", type="smallint")
* #Assert\NotBlank()
*/
private $shirtNumber;
/**
* #var integer $vsid
*
* #ORM\Column(name="vsid", type="integer", nullable=true)
*/
private $vsid;
/**
* #var string $firstname
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* #var string $lastname
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=true)
*/
private $lastname;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #var integer $role
*
* #ORM\Column(type="integer", nullable=true)
*/
private $role;
/**
* Create the user salt
*/
public function __construct()
{
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Player
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set shirtNumber
*
* #param integer $shirtNumber
* #return Player
*/
public function setShirtNumber($shirtNumber)
{
$this->shirtNumber = $shirtNumber;
return $this;
}
/**
* Get shirtNumber
*
* #return integer
*/
public function getShirtNumber()
{
return $this->shirtNumber;
}
/**
* Set vsid
*
* #param integer $vsid
* #return Player
*/
public function setVsid($vsid)
{
$this->vsid = $vsid;
return $this;
}
/**
* Get vsid
*
* #return integer
*/
public function getVsid()
{
return $this->vsid;
}
/**
* Set firstname
*
* #param string $firstname
* #return Player
*/
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 Player
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Player
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set role
*
* #param integer $role
* #return Player
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* #return integer
*/
public function getRole()
{
return $this->role;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Player
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
/**
* Set team
*
* #param Acme\TeamBundle\Entity\Team $team
* #return Player
*/
public function setTeam(\Acme\TeamBundle\Entity\Team $team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return Acme\TeamBundle\Entity\Team
*/
public function getTeam()
{
return $this->team;
}
}
and a Team entity:
<?php
namespace Acme\TeamBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\TeamBundle\Entity\Team
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\TeamBundle\Entity\TeamRepository")
*/
class Team
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $uniqueId
*
* #ORM\Column(name="uniqueId", type="string", length=15)
*/
private $uniqueId;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="teams")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=50)
* #Assert\NotBlank()
*/
private $name;
/**
* #var string $homeColor
*
* #ORM\Column(name="homeColor", type="string", length=7, nullable=true)
*/
private $homeColor;
/**
* #var string $awayColor
*
* #ORM\Column(name="awayColor", type="string", length=7, nullable=true)
*/
private $awayColor;
/**
* #var string $homeShirt
*
* #ORM\Column(name="homeShirt", type="string", length=50, nullable=true)
*/
private $homeShirt;
/**
* #var string $awayShirt
*
* #ORM\Column(name="awayShirt", type="string", length=50, nullable=true)
*/
private $awayShirt;
/**
* #var string $teamLogo
*
* #ORM\Column(name="teamLogo", type="string", length=50, nullable=true)
*/
private $teamLogo;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #ORM\OneToMany(targetEntity="Acme\PlayerBundle\Entity\Player", mappedBy="team", cascade={"persist", "remove"})
*/
private $players;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="homeTeam")
*/
private $homeMatches;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="awayTeam")
*/
private $awayMatches;
/**
* Create the user salt
*/
public function __construct()
{
$this->players = new ArrayCollection();
$this->homeMatches = new ArrayCollection();
$this->awayMatches = new ArrayCollection();
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
public function getMatches()
{
return array_merge($this->awayMatches->toArray(), $this->homeMatches->toArray());
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set uniqueId
*
* #param string $uniqueId
* #return Team
*/
public function setUniqueId($uniqueId)
{
$this->uniqueId = $uniqueId;
return $this;
}
/**
* Get uniqueId
*
* #return string
*/
public function getUniqueId()
{
return $this->uniqueId;
}
/**
* Set name
*
* #param string $name
* #return Team
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set homeColor
*
* #param string $homeColor
* #return Team
*/
public function setHomeColor($homeColor)
{
$this->homeColor = $homeColor;
return $this;
}
/**
* Get homeColor
*
* #return string
*/
public function getHomeColor()
{
return $this->homeColor;
}
/**
* Set awayColor
*
* #param string $awayColor
* #return Team
*/
public function setAwayColor($awayColor)
{
$this->awayColor = $awayColor;
return $this;
}
/**
* Get awayColor
*
* #return string
*/
public function getAwayColor()
{
return $this->awayColor;
}
/**
* Set homeShirt
*
* #param string $homeShirt
* #return Team
*/
public function setHomeShirt($homeShirt)
{
$this->homeShirt = $homeShirt;
return $this;
}
/**
* Get homeShirt
*
* #return string
*/
public function getHomeShirt()
{
return $this->homeShirt;
}
/**
* Set awayShirt
*
* #param string $awayShirt
* #return Team
*/
public function setAwayShirt($awayShirt)
{
$this->awayShirt = $awayShirt;
return $this;
}
/**
* Get awayShirt
*
* #return string
*/
public function getAwayShirt()
{
return $this->awayShirt;
}
/**
* Set teamLogo
*
* #param string $teamLogo
* #return Team
*/
public function setTeamLogo($teamLogo)
{
$this->teamLogo = $teamLogo;
return $this;
}
/**
* Get teamLogo
*
* #return string
*/
public function getTeamLogo()
{
return $this->teamLogo;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Team
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Add players
*
* #param Acme\PlayerBundle\Entity\Player $players
* #return Team
*/
public function addPlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players[] = $players;
return $this;
}
/**
* Remove players
*
* #param Acme\PlayerBundle\Entity\Player $players
*/
public function removePlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players->removeElement($players);
}
/**
* Get players
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPlayers()
{
return $this->players;
}
/**
* Add homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
* #return Team
*/
public function addHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches[] = $homeMatches;
return $this;
}
/**
* Remove homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
*/
public function removeHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches->removeElement($homeMatches);
}
/**
* Get homeMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getHomeMatches()
{
return $this->homeMatches;
}
/**
* Add awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
* #return Team
*/
public function addAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches[] = $awayMatches;
return $this;
}
/**
* Remove awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
*/
public function removeAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches->removeElement($awayMatches);
}
/**
* Get awayMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAwayMatches()
{
return $this->awayMatches;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Team
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
}
Now I've created a player form class with the app/console and I've edited the team field to be an instance of the Team entity, this way:
<?php
namespace Acme\PlayerBundle\Form;
use Acme\TeamBundle\Entity\TeamRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PlayerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('shirtNumber')
->add('firstname')
->add('lastname')
->add('role')
->add('team', 'entity', array(
'class' => 'AcmeTeamBundle:Team',
'query_builder' => function(TeamRepository $er) {
$query = $er->createQueryBuilder('t');
return $query;
}
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\PlayerBundle\Entity\Player',
'csrf_protection' => false
));
}
public function getName()
{
return 'player';
}
}
And this is the relevant part of my controller:
/**
* Create a new player
*
* #Route(".{_format}", name="api_player_create")
* #Method("POST")
* #ApiDoc(
* description="Create a new player",
* statusCodes={
* 201="Player created and informations are returned",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just created
*/
public function createPlayerAction()
{
return $this->processForm(new Player());
}
/**
* Edit a player
*
* #param integer $id The id of the player to be created
*
* #Route("/{id}.{_format}", name="api_player_patch", requirements={ "id": "\d+" })
* #Method("PATCH")
* #ApiDoc(
* description="Edit a player",
* statusCodes={
* 200="Player is updated",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just edited
*/
public function editPlayerAction(Player $player)
{
if ($player->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
return $this->processForm($player);
}
/**
* Function to handle a form to create/edit a player
*
* #param Player $player The player to be created or edited
*
* #return Api Response
*/
private function processForm(Player $player)
{
/**
* Check if the player is new (to be created) or we're editing a player
*/
$statusCode = is_null($player->getId()) ? 201 : 200;
$form = $this->createForm(new PlayerType(), $player);
$form->bind($this->getRequest());
if ($form->isValid()) {
if($player->getTeam()->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
$player->setOwner($this->getUser());
$this->entityManager->persist($player);
$this->entityManager->flush();
return $this->apiResponse->getResponse($player, $statusCode);
}
return $this->apiResponse->getResponse($form, 400, 'Missing arguments');
}
The player creation works fine, the player edit doesn't, when the user makes the api request, passing the ID in the url and the name of the player I get:
Catchable Fatal Error: Argument 1 passed to Acme\PlayerBundle\Entity\Player::setTeam() must be an instance of Acme\TeamBundle\Entity\Team, null given, called in /Volumes/Dati/Users/alessandro/Sites/acme-api/vendor/symfony/symfony/src/Symfony/Component/Form/Util/PropertyPath.php on line 538 and defined in /Volumes/Dati/Users/alessandro/Sites/acme-api/src/Acme/PlayerBundle/Entity/Player.php line 278
Seems that form is trying to set the Team to null, why?
I've tried both sending and not the team as the form parameters but it doesn't work.
Any clue?
Figured it out that null unsent fields in the form is the default behaviour in symfony.
There is an open request for partial form binding in symfony. For now a guy created a form event subscriber that adds the missing fields with the actual values:
https://gist.github.com/3720535
This is his code:
<?php
namespace Foo;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
/**
* Changes Form->bind() behavior so that it treats not set values as if they
* were sent unchanged.
*
* Use when you don't want fields to be set to NULL when they are not displayed
* on the page (or to implement PUT/PATCH requests).
*/
class PatchSubscriber implements EventSubscriberInterface
{
public function onPreBind(FormEvent $event)
{
$form = $event->getForm();
$clientData = $event->getData();
$clientData = array_replace($this->unbind($form), $clientData ?: array());
$event->setData($clientData);
}
/**
* Returns the form's data like $form->bind() expects it
*/
protected function unbind($form)
{
if ($form->hasChildren()) {
$ary = array();
foreach ($form->getChildren() as $name => $child) {
$ary[$name] = $this->unbind($child);
}
return $ary;
} else {
return $form->getClientData();
}
}
static public function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'onPreBind',
);
}
}
to add to the form you have to edit the buildForm method in the form class:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = new PatchSubscriber();
$builder->addEventSubscriber($subscriber);
$builder->add('name');
....
}
In this case you're ok to use the PATCH REST requests to edit an entity just by the sent fields