Symfony 3.4 - Extends bundle Entity - symfony

I'm working with symfony 3.4 and the bundle l3-db-userbundle, i have a problem when I tried add atributtes to the Entity of bundle...
This is my Entity in AppBundle\Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use L3\Bundle\DbUserBundle\Entity\User;
/**
* XUser
*
* #ORM\Table(name="x_user")
* #ORM\Entity
*/
class XUser extends User
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=100, nullable=false)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="apellido", type="string", length=100, nullable=false)
*/
private $apellido;
/**
* #var string
*
* #ORM\Column(name="dni", type="string", length=20, nullable=false)
*/
private $dni;
/**
* #var string
*
* #ORM\Column(name="uid", type="string", length=15, nullable=false)
*/
private $uid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="XRole", inversedBy="user")
* #ORM\JoinTable(name="x_user_role",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $role;
/**
* Constructor
*/
public function __construct()
{
$this->role = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* #param string $id
* #return User
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* #param string $nombre
*/
public function setNombre(string $nombre)
{
$this->nombre = $nombre;
}
/**
* #return string
*/
public function getApellido()
{
return $this->apellido;
}
/**
* #param string $apellido
*/
public function setApellido(string $apellido)
{
$this->apellido = $apellido;
}
/**
* #return string
*/
public function getDni()
{
return $this->dni;
}
/**
* #param string $dni
*/
public function setDni(string $dni)
{
$this->dni = $dni;
}
/**
* #return string
*/
public function getUid()
{
return $this->uid;
}
/**
* Set uid
*
* #param string $uid
* #return User
*/
public function setUid($uid) {
$this->uid = $uid;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getRole()
{
return $this->role;
}
/**
* #param \Doctrine\Common\Collections\Collection $role
*/
public function setRole(\Doctrine\Common\Collections\Collection $role)
{
$this->role = $role;
}
}
And this is the class of vendor
<?php
namespace L3\Bundle\DbUserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="x_user")
* #ORM\Entity(repositoryClass="L3\Bundle\DbUserBundle\Repository \UserRepository")
*/
class User implements UserInterface, \Serializable {
/**
* #var integer $id
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="uid", type="string", length=15)
*/
private $uid;
/**
* #ORM\ManyToMany(targetEntity="Role", cascade={"persist"})
* #ORM\JoinTable(name="x_user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
* #var ArrayCollection $roles
*/
private $roles;
public function __construct() {
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set id
*
* #param string $id
* #return User
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* Get uid
*
* #return string
*/
public function getUid() {
return $this->uid;
}
/**
* Set uid
*
* #param string $uid
* #return User
*/
public function setUid($uid) {
$this->uid = $uid;
return $this;
}
//Source : http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/
public function serialize() {
return serialize(array(
$this->id,
$this->uid
));
}
public function unserialize($serialize) {
list(
$this->id,
$this->uid
) = unserialize($serialize);
}
public function eraseCredentials() {
//pas d'implémentation nécessaire
}
public function getPassword() {
//pas d'implémentation nécessaire
}
public function getRoles() {
$roles = array();
foreach ($this->roles as $role) {
if (!in_array($role->getRole(), $roles)) {
$roles[] = $role->getRole();
}
}
$roles[] = "ROLE_USER";
return $roles;
}
public function getSalt() {
//pas d'implémentation nécessaire
}
public function getUsername() {
return $this->getUid();
}
public function __toString() {
return $this->getUid();
}
}
When I try to get data from database, it show me an error: Attempted to call an undefined method named "getNombre" of class "L3\Bundle\DbUserBundle\Entity\User".
This is the method where i have the problem:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\XUser;
use AppBundle\Entity\XUserOffice;
use AppBundle\Form\UserType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class UserController
* #Route("/users")
*/
class UserController extends Controller
{
/**
* #Route("/", name="users_list")
* #Template("#App/user/index.html.twig")
*/
public function indexAction(Request $request)
{
$users = $this->getDoctrine()->getRepository('AppBundle:XUser')->findAll();
$list = [];
foreach ($users as $user) {
$role = $this->getRole($user->getId());
$dat['id'] = $user->getId();
$dat['name'] = $user->getNombre() . ' ' . $user->getApellido();
$dat['dni'] = $user->getDni();
$dat['role'] = $role['role'];
$list[] = $dat;
}
return [
'list' => $list
];
}

Related

Authentication Symfony is not working

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

How to Work with Doctrine Associations / Relations dosen't work

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

Expected value of type "SourcingBundle\Entity\RequestForEstimate" for association field

I get the following error:
Expected value of type "SourcingBundle\Entity\RequestForEstimate" for
association field
"SourcingBundle\Entity\RequestForEstimateDetail#$detail", got
"Doctrine\Common\Collections\ArrayCollection" instead.
I'm trying to create a structure where there is a RequestForEstimate entity that may have multiple RequestForEstimateDetails nodes. Simply each row in the RequestForEstimateDetails will have a request for a different product and its details when RequestForEstimate only the common information. I'm new to Symfony and I struggle at the point where I want to save the parent element together with the children in the DB. I have been following this Symfony tutorial: How to Embed a Collection of Forms
Here is my code:
SourcingBundle\Entity\RequestForEstimate:
<?php
namespace SourcingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RequestForEstimate
*
* #ORM\Table(name="request_for_estimate")
* #ORM\Entity(repositoryClass="SourcingBundle\Repository\RequestForEstimateRepository")
*/
class RequestForEstimate
{
/**
* #var int
*
* #ORM\Column(name="request_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="update_time", type="datetime")
*/
private $updateTime;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="RequestForEstimateDetail", mappedBy="detail", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $details;
/**
* Get id
*
* #return int
*/
/**
* Constructor
*/
public function __construct()
{
$this->details = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set status
*
* #param integer $status
*
* #return RequestForEstimate
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return RequestForEstimate
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return RequestForEstimate
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
/**
* Set name
*
* #param string $name
*
* #return RequestForEstimate
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add detail
*
* #param \SourcingBundle\Entity\RequestForEstimateDetail $detail
*
* #return RequestForEstimate
*/
public function addDetail(\SourcingBundle\Entity\RequestForEstimateDetail $detail)
{
$this->details[] = $detail;
return $this;
}
/**
* Remove detail
*
* #param \SourcingBundle\Entity\RequestForEstimateDetail $detail
*/
public function removeDetail(\SourcingBundle\Entity\RequestForEstimateDetail $detail)
{
$this->details->removeElement($detail);
}
/**
* Get details
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDetails()
{
return $this->details;
}
}
SourcingBundle\Entity\RequestForEstimateDetail:
<?php
namespace SourcingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RequestForEstimateDetail
*
* #ORM\Table(name="request_for_estimate_detail")
* #ORM\Entity(repositoryClass="SourcingBundle\Repository\RequestForEstimateDetailRepository")
*/
class RequestForEstimateDetail
{
/**
* #var int
*
* #ORM\Column(name="request_detail_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="RequestForEstimate", inversedBy="details")
* #ORM\JoinColumn(name="request_id", referencedColumnName="request_id")
*/
private $detail;
/**
* #var int
*
* #ORM\Column(name="product_id", type="integer")
*/
private $productId;
/**
* #var int
*
* #ORM\Column(name="quantity", type="integer")
*/
private $quantity;
/**
* #var string
*
* #ORM\Column(name="price_per_unit", type="decimal", precision=2, scale=0)
*/
private $pricePerUnit;
/**
* #var string
*
* #ORM\Column(name="shipping_cost", type="decimal", precision=2, scale=0)
*/
private $shippingCost;
/**
* #var string
*
* #ORM\Column(name="other_fees", type="decimal", precision=2, scale=0)
*/
private $otherFees;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set product
*
* #param integer $product
*
* #return RequestForEstimateDetail
*/
public function setProduct($product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return int
*/
public function getProduct()
{
return $this->product;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return RequestForEstimateDetail
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set pricePerUnit
*
* #param string $pricePerUnit
*
* #return RequestForEstimateDetail
*/
public function setPricePerUnit($pricePerUnit)
{
$this->pricePerUnit = $pricePerUnit;
return $this;
}
/**
* Get pricePerUnit
*
* #return string
*/
public function getPricePerUnit()
{
return $this->pricePerUnit;
}
/**
* Set shippingCost
*
* #param string $shippingCost
*
* #return RequestForEstimateDetail
*/
public function setShippingCost($shippingCost)
{
$this->shippingCost = $shippingCost;
return $this;
}
/**
* Get shippingCost
*
* #return string
*/
public function getShippingCost()
{
return $this->shippingCost;
}
/**
* Set otherFees
*
* #param string $otherFees
*
* #return RequestForEstimateDetail
*/
public function setOtherFees($otherFees)
{
$this->otherFees = $otherFees;
return $this;
}
/**
* Get otherFees
*
* #return string
*/
public function getOtherFees()
{
return $this->otherFees;
}
/**
* Set requestId
*
* #param \SourcingBundle\Entity\RequestForEstimate $requestId
*
* #return RequestForEstimateDetail
*/
public function setRequestId(\SourcingBundle\Entity\RequestForEstimate $requestId = null)
{
$this->requestId = $requestId;
return $this;
}
/**
* Get requestId
*
* #return \SourcingBundle\Entity\RequestForEstimate
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Set productId
*
* #param \SourcingBundle\Entity\Product $productId
*
* #return RequestForEstimateDetail
*/
public function setProductId(\SourcingBundle\Entity\Product $productId = null)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId
*
* #return \SourcingBundle\Entity\Product
*/
public function getProductId()
{
return $this->productId;
}
/**
* Set detail
*
* #param \SourcingBundle\Entity\RequestForEstimate $detail
*
* #return RequestForEstimateDetail
*/
public function setDetail(\SourcingBundle\Entity\RequestForEstimate $detail = null)
{
$this->detail = $detail;
return $this;
}
/**
* Get detail
*
* #return \SourcingBundle\Entity\RequestForEstimate
*/
public function getDetail()
{
return $this->detail;
}
/**
* Constructor
*/
public function __construct()
{
$this->detail = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add detail
*
* #param \SourcingBundle\Entity\RequestForEstimate $detail
*
* #return RequestForEstimateDetail
*/
public function addDetail(\SourcingBundle\Entity\RequestForEstimate $detail)
{
$this->detail[] = $detail;
return $this;
}
/**
* Remove detail
*
* #param \SourcingBundle\Entity\RequestForEstimate $detail
*/
public function removeDetail(\SourcingBundle\Entity\RequestForEstimate $detail)
{
$this->detail->removeElement($detail);
}
}
My controller:
<?php
namespace SourcingBundle\Controller;
use SourcingBundle\Entity\RequestForEstimate;
use SourcingBundle\Entity\RequestForEstimateDetail;
use SourcingBundle\Form\Type\RequestForEstimateType;
use SourcingBundle\Form\Type\RequestForEstimateDetailType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class RequestForEstimateController extends Controller
{
/**
* #Route("sourcing/request-for-estimate", name="request_for_estimate")
*/
public function addRequest(Request $request)
{
$RequestForEstimate = new RequestForEstimate();
$form = $this->createForm(RequestForEstimateType::class, $RequestForEstimate);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$request = $form->getData();
foreach($form->get('details')->getData() as $detail)
{
$request->addDetail($detail);
}
print_r($form->get('details')->getData());
$request->setStatus(0);
$request->setupdateTime(new \DateTime());
$request->setcreateTime(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($request);
$em->flush();
return $this->redirectToRoute('RequestsForEstimate');
}
return $this->render('sourcing/requestforestimate/create.html.twig', array(
'form' => $form->createView(),
));
}
}
My forms:
<?php
namespace SourcingBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class RequestForEstimateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('details', CollectionType::class, array(
'entry_type' => RequestForEstimateDetailType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
));
$builder->add('save', SubmitType::class, array('label' => 'Create Request'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SourcingBundle\Entity\RequestForEstimate',
));
}
}
<?php
namespace SourcingBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RequestForEstimateDetailType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('quantity');
$builder->add('pricePerUnit');
$builder->add('shippingCost');
$builder->add('otherFees');
// $builder->add('product');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SourcingBundle\Entity\RequestForEstimateDetail',
));
}
}
In the RequestForEstimateDetail the getter/setter method of the field detail are for manage the collection itself (the add/remove methods are for the single element of the collection), so modify the getter/setter method to handle an ArrayCollection object.
As Example:
RequestForEstimateDetail
/**
* Set detail
*
* #param \Doctrine\Common\Collections\ArrayCollection an array of $detail
*
* #return RequestForEstimateDetail
*/
public function setDetail(\Doctrine\Common\Collections\ArrayCollection $detail = null)
{
$this->detail = $detail;
return $this;
}
/**
* Get detail
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getDetail()
{
return $this->detail;
}
Hope this help
Well, the existing addDetail method in the RequestForEstimate entity did the trick:
public function addDetail(\SourcingBundle\Entity\RequestForEstimateDetail $detail)
{
$this->details->add($detail);
$detail->setDetail($this);
return $this;
}

Symfony does not remove Element from ArrayCollection

i want to remove an role from the roles-ArrayCollection in the User Entity.
User and Role have an M:N connection.
In my Controller:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($userId);
$user->removeRole($roleID);
$em->flush();
If I execute the controller, there are no error messages.
But the Role is still assigned to the user.
User Entity
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="usermanagement_users")
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface,\Serializable
{
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
$this->isActive = true;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->roles->toArray();
}
public function setRoles($roles){
$this->roles[] = $roles;
}
public function removeRole($role){
unset($this->roles->toArray()[$role]);
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=60)
*/
private $vorname;
/**
* #ORM\Column(type="string", length=60)
*/
private $nachname;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $letzterLogin;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function setId($id){
$this->id = $id;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
Role Entity
<?php
/**
* Created by PhpStorm.
* User: christianschade
* Date: 02.02.15
* Time: 19:29
*/
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Role
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\RoleRepository")
* #ORM\Table(name="usermanagement_roles")
*/
class Role implements RoleInterface {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
public function getRole() {
return $this->role;
}
/**
* #ORM\ManyToMany(targetEntity = "User", inversedBy = "roles")
*
* #var ArrayCollection $users
*/
protected $users;
/**
* #return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* #param ArrayCollection $users
*/
public function setUsers($users)
{
$this->users = $users;
}
public function setRoles($roles)
{
$this->role = $roles;
// allows for chaining
return $this;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #ORM\ManyToMany(targetEntity = "Chris\UserBundle\Entity\Group", inversedBy = "groups")
*
* #var ArrayCollection $group
*/
private $group;
/**
* #return ArrayCollection
*/
public function getGroup()
{
return $this->group;
}
/**
* #param ArrayCollection $group
*/
public function setGroup($group)
{
$this->group = $group;
}
}
You should use ArrayCollection::removeElement() to remove the role.
public function removeRole($role)
{
$this->roles->removeElement($role);
}
On a side note, I feel your getRoles() implementation is unorthodox as it would be recommended to return the ArrayCollection as is and call toArray() if you need to once you have retrieved it.
public function getRoles()
{
return $this->roles;
}

Symfony: User roles with doctrine: no entities or tables created

I followed the instructions given in the Symfony-Book to get a user-role relation with doctrine updating them in my database.
Symfony - User/Role - Doctrine
But when I update my entities via doctrine:generate:entities, it only generates the existing User.php, but doesn't touch the Role.php. This wouldn't bother me, if the tables in my databse would update with doctrine:schema:update --force. But they don't. The mentioned tables aren't created. In fact, nothing happens. Can you please help me? I am looking forward to any good solution.
My User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=24, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="isActive", type="string", length=255, nullable=false)
*/
private $isactive;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=10, nullable=false)
*/
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
private $roles;
public function __construct()
{
$this->isActive = true;
$this->roles = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return $this->roles->toArray();
}
/**
* 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 isactive
*
* #param string $isactive
* #return User
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return string
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* #var string
*/
private $type;
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
}
Role.php:
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="user_role")
* #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)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
}
First tip: give your user table a different name, eg #ORM\Table(name="acme_user").
Second: add in your user class:
/**
* User's roles.
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
and in your role class
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
#see: http://symfony.com/doc/2.3/cookbook/security/entity_provider.html

Resources