Hy everybody, i've got a problem with my Bundle when I'm trying to obtain the ID of an user.
$user = $userManager->findUserById($tmpID['uid']);
Where $tmpID['uid'] is the ID of the user and when I'm trying to to $user->getId() I obtain an error.
This is the error
FatalErrorException: Error: Call to a member function getId() on a non-object in /Applications/MAMP/htdocs/Api/src/Api/ApiBundle/Controller/DefaultController.php line 263
MyBundle\Entity\User.php
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* #var integer
*
* #ORM\Column(name="genre", type="integer", nullable=false)
*/
protected $genre;
/**
* #var string
*
* #ORM\Column(name="device", type="string", nullable=true)
*/
protected $device;
/**
* #var string
*
* #ORM\Column(name="avatar", type="string", nullable=true)
*/
protected $avatar;
/**
* #var string
*
* #ORM\Column(name="phone", type="integer", nullable=true)
*/
protected $phone;
public function __construct()
{
parent::__construct();
// your own logic
}
public function getDescription() {
return $this->description;
}
public function setDescription($description) {
$this->description = $description;
}
public function getGenre() {
return $this->genre;
}
public function setGenre($genre) {
$this->genre = $genre;
}
public function getDevice() {
return $this->device;
}
public function setDevice($device) {
$this->device = $device;
}
public function getPhone() {
return $this->phone;
}
public function setPhone($phone) {
$this->phone = $phone;
}
public function getAvatar() {
return $this->avatar;
}
public function setAvatar($avatar) {
$this->avatar = $avatar;
}
}
While i was going to the office I get the solution! :)
On my function $tmpIDis an variable wich has the token of an user when that used login into Symfony. The problem it was I was using a token of an user wich didn't exist into the DDBB (Yes, i erased the user 5 minutes before to get that error)
Then, i was trying to obtain a non-existent user and that's the reason why i get NULL for $user
I hope my problem can help other people.
p.s. Thanks to #Javad and #George for the suggestions
Related
I am trying to implement sorting in my Symfony 6 project.
Here is the entity I am trying to sort :
<?php
namespace App\Entity;
use App\Entity\Workflow\Status;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Plant;
use App\Entity\DetailedCause;
/**
* #ORM\Entity(repositoryClass=\App\Repository\RequestRepository::class)
*/
class Request
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $requesterName;
/**
* #ORM\Column(type="string")
*/
private $requesterService;
/**
* #ORM\Column(type="string")
*/
private $requesterMatricule;
/**
* #ORM\Column(type="integer")
*/
private $priority;
/**
* #ORM\Column(type="integer")
*/
private $type;
/**
* #ORM\Column(type="boolean")
*/
private $flagSupp;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $estimatedLoad;
/**
* #ORM\Column(type="text")
*/
private $reason;
/**
* #ORM\Column(type="datetime", nullable=false)
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity=Workflow\Status::class)
* #ORM\JoinColumn(nullable=false)
*/
private Status $state;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $product;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $program;
/**
* #ORM\ManyToOne(targetEntity=DetailedCause::class)
* #ORM\JoinColumn(nullable=false)
*/
private DetailedCause $detailedCause;
/**
* #ORM\ManyToOne(targetEntity=Cause::class)
*/
private $cause;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $impactedPlant;
/**
* #ORM\OneToMany(targetEntity=Action::class, mappedBy="request")
*/
private $actions;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $requesterPlant;
public function __construct()
{
$this->actions = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRequesterPlant(): ?Plant
{
return $this->requesterPlant;
}
public function setRequesterPlant(?Plant $requesterPlant): self
{
$this->requesterPlant = $requesterPlant;
return $this;
}
//the rest of getters and setters
}
and the repository :
<?php
namespace App\Repository;
use App\Entity\Request;
use App\Entity\RequestFilter;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Plant;
/**
* #method Request|null find($id, $lockMode = null, $lockVersion = null)
* #method Request|null findOneBy(array $criteria, array $orderBy = null)
* #method Request[] findAll()
* #method Request[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
* #method Paginator getRequestPaginator(int $offset = 0, string $order = 'id')
*/
class RequestRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Request::class);
}
/**
* #var int $offset
* #param RequestFilter
* #return Paginator Returns a paginator of requests using filters
*/
public function getRequestPaginator($offset = 0, RequestFilter $filter = null)
{
if ($filter == null) {
$filter = new RequestFilter();
}
#adds filter parameters to the query
$query = $this->createQueryBuilder('r');
if ($filter->getStates() != null){
$query
->andWhere('r.state IN (:states)')
->setParameter('states', $filter->getStates());//;
}
#adds the rest of the params
$query = $query
//this orderBy clause is triggering the error
->orderBy('r.' . $filter->getOrder(), $filter->getOrderDirection())
->setFirstResult($offset)
->setMaxResults($filter->getRequestsPerPage())
->getQuery();
return new Paginator($query);
}
}
this works fine for most attributes. I can sort by date, requester name, etc.
But when I try to sort by requesterPlant, which is a doctrine Entity, I get the following error :
("An exception occurred while executing a query: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r0_.requester_plant_id' in 'field list'").
This column does exist in the database just like other columns. I do not understand why doctrine is stuck on this. Migrations are up to date, I've cleared cache, and I've been stuck on this problem for days.
I would really appreciate if anyone had a clue about what is happening there.
As additional info, here is my Plant entity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=\App\Repository\PlantRepository::class)
*/
class Plant
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #ORM\OneToMany(targetEntity="App\Entity\Request", mappedBy="requesterPlant")
*/
private int $id;
/**
* #ORM\Column(type="string", length=255)
*/
private string $designation;
/**
* #ORM\Column(type="string", length=50)
*/
private string $plantString;
/**
* #ORM\Column(type="string", length=50)
*/
private string $company;
public function getId(): ?int
{
return $this->id;
}
public function setID(int $id): self
{
$this->id = $id;
return $this;
}
public function getDesignation(): ?string
{
return $this->designation;
}
public function setDesignation(string $designation): self
{
$this->designation = $designation;
return $this;
}
public function getPlantString(): ?string
{
return $this->plantString;
}
public function setPLantString(string $plantString): self
{
$this->plantString = $plantString;
return $this;
}
public function getCompany(): ?string
{
return $this->company;
}
public function setCompany(string $company): self
{
$this->company = $company;
return $this;
}
}
I have a Evaluation entity which has one Product and Product which can have several Evaluations. I'm trying to fetch one Product and to get the list of Evaluations associated with my entity
Produit.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use phpDocumentor\Reflection\Types\This;
/**
* Produit
*
* #ORM\Table(name="produit", indexes={#ORM\Index(name="fk_idcatedel", columns={"idCategorie"})})
* #ORM\Entity
*/
class Produit
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string|null
*
* #ORM\Column(name="libelle", type="string", length=20, nullable=true)
*/
private $libelle;
/**
* #var float|null
*
* #ORM\Column(name="prix", type="float", precision=10, scale=0, nullable=true)
*/
private $prix;
/**
* #var string|null
*
* #ORM\Column(name="description", type="string", length=50, nullable=true)
*/
private $description;
/**
* #var int
*
* #ORM\Column(name="qt", type="integer", nullable=false)
*/
private $qt;
/**
* #var string|null
*
* #ORM\Column(name="img", type="string", length=255, nullable=true)
*/
private $img;
/**
* #var \Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idCategorie", referencedColumnName="id")
* })
*/
private $idcategorie;
/**
* #ORM\OneToMany(targetEntity="Evaluation", mappedBy="idProduit")
*/
private $rates;
public function __construct()
{
$this->rates = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLibelle(): ?string
{
return $this->libelle;
}
public function setLibelle(?string $libelle): self
{
$this->libelle = $libelle;
return $this;
}
public function getPrix(): ?float
{
return $this->prix;
}
public function setPrix(?float $prix): self
{
$this->prix = $prix;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getQt(): ?int
{
return $this->qt;
}
public function setQt(int $qt): self
{
$this->qt = $qt;
return $this;
}
public function getImg(): ?string
{
return $this->img;
}
public function setImg(?string $img): self
{
$this->img = $img;
return $this;
}
public function getIdcategorie(): ?Categorie
{
return $this->idcategorie;
}
public function setIdcategorie(?Categorie $idcategorie): self
{
$this->idcategorie = $idcategorie;
return $this;
}
/**
* #return Collection|Evaluation[]
*/
public function getRates(): Collection
{
return $this->rates;
}
}
Evaluation.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Evaluation
*
* #ORM\Table(name="evaluation", indexes={#ORM\Index(name="fk_idprodevaldel", columns={"id_produit"}), #ORM\Index(name="fk_iduser", columns={"id_user"})})
* #ORM\Entity
*/
class Evaluation
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="note", type="integer", nullable=false)
*/
private $note;
/**
* #var \Produit
*
* #ORM\ManyToOne(targetEntity="Produit", inversedBy="rates")
* #ORM\JoinColumn(name="id_produit", referencedColumnName="id")
*/
private $idProduit;
/**
* #var \Compte
*
* #ORM\ManyToOne(targetEntity="Compte")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_user", referencedColumnName="email")
* })
*/
private $idUser;
public function getId(): ?int
{
return $this->id;
}
public function getNote(): ?int
{
return $this->note;
}
public function setNote(int $note): self
{
$this->note = $note;
return $this;
}
public function getIdProduit(): ?Produit
{
return $this->idProduit;
}
public function setIdProduit(?Produit $idProduit): self
{
$this->idProduit = $idProduit;
return $this;
}
public function getIdUser(): ?Compte
{
return $this->idUser;
}
public function setIdUser(?Compte $idUser): self
{
$this->idUser = $idUser;
return $this;
}
}
The database
In my controller I succeed to get informations from the products but rates are empty
$produits = $this->getDoctrine()
->getRepository(Produit::class)
->find(1);
dump($produits);
$rates = $produits->getRates();
dump($rates); // #collection: ArrayCollection is empty
The Output :
The collection is not yet initialized due to lazy loading, and rightfully so. If you don't access at least to an element in the collection, it's pointless to load the whole collection because doctrine can safely assume you'll "discard" it. As soon as you access an element (either by looping onto collection or getting a specific element), the collection will be initialized and you have all items.
Another way is to use an EAGER fetch that will load the whole collection in the hydration phase. I would not reccomend it however, unless you're sure that everytime you load a Produit, you need this collection "ready". Even in the latter case, I would handle the collection "manually" as I recommend not to lose control on it (let's pretend you have A LOT of element inside it).
Read more about proxies and association, here
I´m new on symfony.
I´m getting this error when I try to run
$ php bin/console doctrine:generate:entities LoginBundle:Users
The autoloader expected class "LoginBundle\Entity\Users" to be defined
in file ... The file was found but the class was not in it, the class
name or namespace probably has a typo.
My entity is:
<?
// src/LoginBundle/Entity/Users.php
namespace LoginBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class Users
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="mail", type="string", length=100)
*/
private $mail;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="lastname", type="string", length=30)
*/
private $lastname;
/**
* #ORM\Column(name="password", type="string", length=100)
*/
private $password;
public function getMail()
{
return $this->mail;
}
public function getName()
{
return $this->name;
}
public function getLastname()
{
return $this->lastname;
}
public function getPassword()
{
return $this->password;
}
public function setMail($data)
{
$this->mail = $data;
return;
}
public function setName($data)
{
$this->name = $data;
return;
}
public function setLastname($data)
{
$this->lastname = $data;
return;
}
public function setPassword($data)
{
$this->password = $data;
return;
}
}
The php open tag is wrong, because it's a server configuration about short_open_tag
See the Documentation:
try to change
<?
to
<?php
when i try to display all users for admin interface i get this error
Notice: unserialize(): Error at offset 0 of 6 bytes
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
/**
* Description of AdminController
*
* #author saif
*/
class AdminController extends Controller {
public function valide_compteAction()
{
$em=$this->getDoctrine()->getManager();
$utilisateur=$em->getRepository('WelcomeBundle:Utilisateur')->findall();
return $this->render('AdminBundle:admin:valide_compte.html.twig',array('i'=>$utilisateur));
}
}
and this is my userclass
namespace WelcomeBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use \Symfony\Component\Security\Core\User\AdvancedUserInterface;
use JMS\SerializerBundle\Annotation\Type;
/**
* Utilisateur
*
* #ORM\Table(name="utilisateur")
* #ORM\Entity
*/
class Utilisateur extends BaseUser implements AdvancedUserInterface, \Serializable
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=40, nullable=false)
*/
protected $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=40, nullable=false)
*/
protected $prenom;
/**
* #var integer
*
* #ORM\Column(name="numtelphone", type="integer", nullable=true)
*/
protected $numtelphone;
/**
* #var string
*
* #ORM\Column(name="addresse", type="string", length=40, nullable=true)
*/
protected $addresse;
/**
* #var integer
*
* #ORM\Column(name="jeton", type="integer", nullable=true)
*/
protected $jeton;
/**
* #var string
*
* #ORM\Column(name="photo", type="blob", nullable=true)
*/
protected $photo;
/**
* #var string
*
* #ORM\Column(name="mailreclamation", type="string", length=50, nullable=true)
*/
protected $mailreclamation;
public function __construct()
{
parent::__construct();
// your own logic
}
public function getId() {
return $this->id;
}
public function getNom() {
return $this->nom;
}
public function getPrenom() {
return $this->prenom;
}
public function getNumtelphone() {
return $this->numtelphone;
}
public function getAddresse() {
return $this->addresse;
}
public function getJeton() {
return $this->jeton;
}
public function getPhoto() {
return $this->photo;
}
public function getMailreclamation() {
return $this->mailreclamation;
}
public function setId($id) {
$this->id = $id;
}
public function setNom($nom) {
$this->nom = $nom;
}
public function setPrenom($prenom) {
$this->prenom = $prenom;
}
public function setNumtelphone($numtelphone) {
$this->numtelphone = $numtelphone;
}
public function setAddresse($addresse) {
$this->addresse = $addresse;
}
public function setJeton($jeton) {
$this->jeton = $jeton;
}
public function setPhoto($photo) {
$this->photo = $photo;
}
public function setMailreclamation($mailreclamation) {
$this->mailreclamation = $mailreclamation;
}
public function json_encode()
{
return json_encode(array(
$this->password,
$this->salt,
$this->usernameCanonical,
$this->username,
$this->expired,
$this->locked,
$this->credentialsExpired,
$this->enabled,
$this->id,
));
}
}
how can i solve this, i have wasted a lot of time in this
Check the serialized data in the database. Are they consistent? It is possible that the database driver assumes another data type. In this case check the blob type for the photo column. I had had a similar problem with json/array type.
I haven't found any solid example on how to do this.
I have my entity Shield, which can have more than 1 ShieldTypes. What I want to do is, create a form that creates a new Shield with different Shieldtypes.
This is my code, I honestly don't know where is my error:
Error is:
Entities passed to the choice field must be managed
500 Internal Server Error - FormException
Armory\SearchBundle\Entity\Shield.php
namespace Armory\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Armory\SearchBundle\Entity\Shield
*
* #ORM\Table(name="shield")
* #ORM\Entity
*/
class Shield
{
/**
* #var integer $id
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var integer $defense
* #ORM\Column(name="defense", type="integer", nullable=false)
*/
private $defense;
/**
* #var boolean $active
* #ORM\Column(name="active", type="boolean", nullable=false)
*/
private $active;
/**
* #ORM\ManyToMany(targetEntity="ShieldTypes")
* #ORM\JoinTable(name="i_orbs_type",
* joinColumns={#ORM\JoinColumn(name="id_orb", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id_type", referencedColumnName="id")}
* )
* #var ArrayCollection $types
*/
protected $types;
public function __construct(){
$this->types = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getTypes(){
return $this->types;
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setDefense($defense)
{
$this->defense = $defense;
}
public function getDefense()
{
return $this->defense;
}
public function setActive($active)
{
$this->active = $active;
}
public function getActive()
{
return (bool)$this->active;
}
}
Armory\SearchBundle\Form\ShieldType.php:
namespace Armory\SearchBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ShieldType extends AbstractType{
public function buildForm(FormBuilder $builder, array $options){
$builder->add('name','text');
$builder->add('defense','integer');
$builder->add('active','checkbox');
$builder->add('types','entity',
array(
'class'=>'Armory\SearchBundle\Entity\ShieldTypes',
'query_builder'=> function($repository){
return $repository->createQueryBuilder('t')->orderBy('t.id', 'ASC');
},
'property'=>'name', )
);
}
public function getName(){
return 'shield';
}
public function getDefaultOptions(array $options){
return array('data_class'=>'Armory\\SearchBundle\\Entity\\Shield');
}
}
Armory\SearchBundle\Entity\ShieldTypes.php
namespace Armory\SearchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SOA\CRMBundle\Entity\ShieldTypes
*
* #ORM\Table(name="orbs_type")
* #ORM\Entity
*/
class ShieldTypes
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string $title
*
* #ORM\Column(name="title", type="string", length=45, nullable=false)
*/
private $title;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
It can be a little confusing but:
Shield entity (database)
ShieldTypes entity (database)
ShieldType form (abstracttype)
Thank you...
So the problem was that I didn't create a repository. I created it (see code at the end) and I still got 'Entities passed to the choice field must be managed' error.
Then I set mutiple to true in:
$builder->add('types','entity',
array(
'class'=>'Armory\SearchBundle\Entity\ShieldTypes',
'query_builder'=> function(\Armory\SearchBundle\Entity\Repository\ShieldTypesRepository $repository){
return $repository->createQueryBuilder('s')->orderBy('s.id', 'ASC');},
'property'=>'title',
'multiple'=>true
)
);
I hope someone finds this useful, cause if I had had this, it would been easier.
Code for my repository:
namespace Armory\SearchBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class ShieldTypesRepository extends EntityRepository
{
public function getAll()
{
return $this->_em->createQuery('SELECT s FROM Armory\SearchBundle\Entity\ShieldTypes s')
->getResult();
}
}