How to join many to many in createQuery() - symfony

I'm working on my portfolio, and I got a page where I show my project. I created 2 cayegorie for now: Programmation and artistic. Each of my project can be a programming project, an artistique project or both. There for, I made a table project and a table categorie and they are join with a many to many relationship. So far, no probleme.
I started to create my query in the repository file of my project entitie. The problem is when I try to join my project entitie and my categorie entitie, it doesn't look like it works, because I specefy that I want just the project that have at least programmation for categorie at least. But it still returns me ALL the project when it should only give me 2 of them.
Did I made my JOIN right?
Here are the entities (watch out for the french!):
Project:
<?php
namespace PublicBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Projet
*
* #ORM\Table(name="pt_projet");
* #ORM\Entity
* #ORM\Entity(repositoryClass="PublicBundle\Entity\ProjetDepot")
*/
class Projet
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
//ID du projet
protected $id;
/**
* #ORM\Column(name="pro_tag", type="string",length=255, unique=true)
*/
//Tag du projet
protected $tag;
/**
* #ORM\OneToMany(targetEntity="ProjetInt", mappedBy="projetId", orphanRemoval=true)
*/
protected $descriptions;
/**
* #ORM\Column(name="pro_img", type="string", length=64, unique=true)
*/
//Nom du fichier de l'image du projet
protected $image;
/**
* #ORM\Column(name="pro_technologie_utilisee", type="text", length=200)
*/
//Text qui liste tout les technologies utilisées pour le projet
protected $technologie;
/**
* #ORM\Column(name="pro_annee", type="integer", length=4)
*/
//Année de réalisation du projet
protected $annee;
/**
* #ORM\ManyToOne(targetEntity="Type", inversedBy="projets")
* #ORM\JoinColumn(name="pro_type", referencedColumnName="id", nullable=false)
*/
//Clef étrangère du type de projet
//Le type de projet ne correspond pas à la catégore. Il peu être Unity, flash, image, vidéo, etc. Il permet de savoir quelle page charger pour pouvoir intégrer le projet dans le portfolio.
protected $type;
/**
* #ORM\Column(name="pro_fichier", type="string", length=64, unique=true)
*/
//Nom du fichier du projet
private $fichier;
/**
* #ORM\ManyToMany(targetEntity="Categorie", cascade={"persist"})
*/
//La ou les catégories du projet
private $categories;
/**
* Constructor
*/
public function __construct()
{
$this->descriptions=new ArrayCollection();
$this->categories=new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set image
*
* #param string $image
* #return Projet
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set technologie
*
* #param string $technologie
* #return Projet
*/
public function setTechnologie($technologie)
{
$this->technologie = $technologie;
return $this;
}
/**
* Get technologie
*
* #return string
*/
public function getTechnologie()
{
return $this->technologie;
}
/**
* Set annee
*
* #param integer $annee
* #return Projet
*/
public function setAnnee($annee)
{
$this->annee = $annee;
return $this;
}
/**
* Get annee
*
* #return integer
*/
public function getAnnee()
{
return $this->annee;
}
/**
* Set fichier
*
* #param string $fichier
* #return Projet
*/
public function setFichier($fichier)
{
$this->fichier = $fichier;
return $this;
}
/**
* Get fichier
*
* #return string
*/
public function getFichier()
{
return $this->fichier;
}
/**
* Set type
*
* #param Type $type
* #return Projet
*/
public function setType(Type $type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return Type
*/
public function getType()
{
return $this->type;
}
/**
* Add categories
*
* #param Categorie $categories
* #return Projet
*/
public function addCategory(Categorie $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove categories
*
* #param Categorie $categories
*/
public function removeCategory(Categorie $categories)
{
$this->categories->removeElement($categories);
}
/**
* Get categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Add description
*
* #param \PublicBundle\Entity\ProjetInt $description
* #return Projet
*/
public function addDescription(\PublicBundle\Entity\ProjetInt $description)
{
$this->description[] = $description;
return $this;
}
/**
* Remove description
*
* #param \PublicBundle\Entity\ProjetInt $description
*/
public function removeDescription(\PublicBundle\Entity\ProjetInt $description)
{
$this->description->removeElement($description);
}
/**
* Get description
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDescription()
{
return $this->description;
}
}
Category:
<?php
namespace PublicBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Catégorie
*
* #ORM\Table(name="pt_categorie");
* #ORM\Entity
* #ORM\Entity(repositoryClass="PublicBundle\Entity\CategorieDepot")
*/
class Categorie
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
//ID de la catégorie
protected $id;
/**
* #ORM\Column(name="cat_tag", type="string",length=255, unique=true)
*/
//Tag de la catégorie
protected $tag;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Categorie
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
return $this->tag;
}
}
And the reposetory:
<?php
namespace PublicBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ProjetDepot
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProjetDepot extends EntityRepository
{
public function rechercherProjets($lang, $cat)
{
return $this->getEntityManager()->createQuery(
'SELECT p.tag,
p.image,
pi.nom,
pi.descriptionCours,
pi.descriptionComplete,
pi.roles,
p.technologie,
pi.aptitudesDeveloppees,
p.annee
FROM PublicBundle:Projet p
JOIN PublicBundle:ProjetInt pi
WITH p.id=pi.projetId
JOIN PublicBundle:Categorie c
WHERE pi.langue=:lang
AND c.tag=:cat'
)->setParameters(array('lang'=>$lang,'cat'=>$cat))->getResult();
}
}

Try this
public function rechercherProjets($lang, $cat) {
$qb = $this->createQueryBuilder('p')
->innerJoin ('p.description', 'pi')
->innerJoin('p.categories', 'pc')
->andWhere('pc.tag = :cat')
->andWhere('pi.langue = :lang')
->setParameters(array('lang'=>$lang,'cat'=>$cat));
return $qb->getQuery()->getResult()
}

Related

Doctrine OneToMany relation returns nothing

Context
I have a User entity which has one Team and Team which can have several users.
I'm trying to fetch one team and to get the list of users associated with.
User Entity
<?php
namespace Enterprise\PortailBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User entity class
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Enterprise\PortailBundle\Repository\TeamRepository")
* #category Entity
* #package Entity
*/
class User
{
/*
* Relationship Mapping Metadata
*/
public function __toString()
{
return $this->firstName . ' - ' . $this->lastName . ' - ' . $this->enterprise . ' - ' . $this->team;
}
/**
* #ORM\ManyToOne(targetEntity="Team", inversedBy="users")
* #ORM\JoinColumn(name="team_id", referencedColumnName="id")
*/
private $team;
/*
* Autogenerated methods / variables
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le prénom de l'utilisateur doit être supérieur à 2 caractères.")
* #Assert\Length(max=32, maxMessage="Le prénom de l'utiisateur doit être inférieur à 32 caractères.")
* #ORM\Column(name="firstName", type="string", length=32)
*/
private $firstName;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'utilisateur doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'utilisateur doit être inférieur à 64 caractères.")
* #ORM\Column(name="lastName", type="string", length=64)
*/
private $lastName;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'entreprise doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'entreprise doit être inférieur à 64 caractères.")
* #ORM\Column(name="enterprise", type="string", length=64)
*/
private $enterprise;
/**
* #Assert\File(mimeTypes={ "image/jpeg", "image/jpg", "image/png" })
* #ORM\Column(name="image", type="string")
*/
private $image;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* 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 enterprise
*
* #param string $enterprise
*
* #return User
*/
public function setEnterprise($enterprise)
{
$this->enterprise = $enterprise;
return $this;
}
/**
* Get enterprise
*
* #return string
*/
public function getEnterprise()
{
return $this->enterprise;
}
/**
* Set image
*
* #param string $image
*
* #return User
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set team
*
* #param Team $team
*
* #return User
*/
public function setTeam(Team $team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return Team
*/
public function getTeam()
{
return $this->team;
}
}
Team entity
<?php
namespace Enterprise\PortailBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Team entity class
*
* #ORM\Table(name="team")
* #ORM\Entity(repositoryClass="Enterprise\PortailBundle\Repository\TeamRepository")
* #category Entity
* #package Entity
*/
class Team
{
public function __toString()
{
return $this->name . ' - ' . $this->role;
}
/**
* #ORM\OneToMany(targetEntity="User", mappedBy="team")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/*
* Autogenerated methods / variables
*/
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le nom de l'équipe doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le nom de l'équipe doit être inférieur à 64 caractères.")
* #ORM\Column(name="name", type="string", length=64)
*/
private $name;
/**
* #var string
*
* #Assert\Length(min=2, minMessage="Le role de l'équipe doit être supérieur à 2 caractères.")
* #Assert\Length(max=64, maxMessage="Le role de l'équipe doit être inférieur à 64 caractères.")
* #ORM\Column(name="role", type="string", length=64)
*/
private $role;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* 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;
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Set role
*
* #param string $role
*
* #return Team
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* #return string
*/
public function getRole()
{
return $this->role;
}
}
Doctrine version
2.5.14
The database
The team and the user table
In my controller I succeed to get informations when going from user to the team
$user = $this->getDoctrine()->getRepository(User::class)->find(6);
dump($user);
$teamName = $user->getTeam()->getName();
dump($teamName);
But the contrary doesn't returns me the list of users
$team = $this->getDoctrine()->getRepository(Team::class)->find(1);
dump($team);
$users = $team->getUsers();
dump($users);
The output of this last part is:
So my question is why $users = $team1->getUsers(); doesn't return the list of users ?
Thanks
Probably for efficiency reasons, it seems that Symfony does not populate data until you request them.
Try this, you should see that the collection is not empty anymore, and that you can actually access the user data from a team:
$team = $this->getDoctrine()->getRepository(Team::class)->find(1);
dump($team);
$users = $team->getUsers();
dump($users); // #collection: ArrayCollection is not empty anymore
$firstName = $users[0]->getFirstName();
dump($firstName);

Symfony 3 relation not working with update --force

So, my problem is when I'm trying to update schema with command "dotrine:schema:update --force", entity are create but without any relation.
I have two entity "advert" and "category" and a relation ManyToMany on advert entity.
This is entyty advert :
<?php
namespace testBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Advert
*
* #ORM\Table(name="advert")
* #ORM\Entity(repositoryClass="testBundle\Repository\AdvertRepository")
*/
class Advert
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="categories", type="string", length=255)
* /**
* #ORM\ManyToMany(targetEntity="OC\PlatformBundle\Entity\Category", cascade={"persist"})
*/
private $categories;
public function __construct()
{
$this->date = new \Datetime();
$this->categories = new ArrayCollection();
}
// Notez le singulier, on ajoute une seule catégorie à la fois
public function addCategory(Category $category)
{
// Ici, on utilise l'ArrayCollection vraiment comme un tableau
$this->categories[] = $category;
}
public function removeCategory(Category $category)
{
// Ici on utilise une méthode de l'ArrayCollection, pour supprimer la catégorie en argument
$this->categories->removeElement($category);
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set categories
*
* #param string $categories
*
* #return Advert
*/
public function setCategories($categories)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return string
*/
public function getCategories()
{
return $this->categories;
}
}
My entity category :
<?php
namespace testBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="testBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #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;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
and this is the result of command doctrine:schema:update --force --dump-sql :
CREATE TABLE advert (id INT AUTO_INCREMENT NOT NULL, categories VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
Like you can see, no relation and no table advert_category
I found some topic about this but no solution working for me.
I hope someone can help me
Thank you !
Relation declared wrong, i think it should be something like this :
/**
* #ORM\ManyToMany(targetEntity="testBundle\Entity\Category")
* #ORM\JoinTable(name="advert_category")
*/
private $categories;
So problem fixed, I have to delete this :
*
* #ORM\Column(name="categories", type="string", length=255)
/**
and it's work , thank you #thomas !

Doctrine - Perform select with relationship 1:N

I have a number of entities (automatically generated with Symfony2 Console) that are structured as follows in the database:
The entity generated is as follows:
class Offers
{
/**
* #var string
* #Assert\Length(
* min = 5,
* max = 64,
* minMessage = "El nombre de la oferta debe de tener al menos {{ limit }} caracteres.",
* maxMessage = "El nombre de la oferta no puede superar los {{ limit }} caracteres."
* )
*/
private $name;
/**
* #var string
*/
private $description;
/**
* #var string
* #Assert\Url(message = "La url '{{ value }}' no es válida")
*/
private $url;
/**
* #var string
*/
private $img;
/**
* #var \DateTime
*/
private $dateFrom;
/**
* #var \DateTime
*/
private $dateTo;
/**
* #var \DateTime
*/
private $registered;
/**
* #var boolean
*/
private $active;
/**
* #var integer
*/
private $availableFor;
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $idState;
/**
* Constructor
*/
public function __construct()
{
$this->idState = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set name
*
* #param string $name
* #return Offers
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Offers
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set url
*
* #param string $url
* #return Offers
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set img
*
* #param string $img
*/
public function setImg($img = null)
{
if ( $img != null)
$this->img = $img;
}
/**
* Get img
*
* #return string
*/
public function getImg()
{
return $this->img;
}
/**
* Set dateFrom
*
* #param \DateTime $dateFrom
* #return Offers
*/
public function setDateFrom($dateFrom)
{
$this->dateFrom = $dateFrom;
return $this;
}
/**
* Get dateFrom
*
* #return \DateTime
*/
public function getDateFrom()
{
return $this->dateFrom;
}
/**
* Set dateTo
*
* #param \DateTime $dateTo
* #return Offers
*/
public function setDateTo($dateTo)
{
$this->dateTo = $dateTo;
return $this;
}
/**
* Get dateTo
*
* #return \DateTime
*/
public function getDateTo()
{
return $this->dateTo;
}
/**
* Set registered
*
* #param \DateTime $registered
* #return Offers
*/
public function setRegistered($registered)
{
$this->registered = $registered;
return $this;
}
/**
* Get registered
*
* #return \DateTime
*/
public function getRegistered()
{
return $this->registered;
}
/**
* Set active
*
* #param boolean $active
* #return Offers
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set availableFor
*
* #param integer $availableFor
* #return Offers
*/
public function setAvailableFor($availableFor)
{
$this->availableFor = $availableFor;
return $this;
}
/**
* Get availableFor
*
* #return integer
*/
public function getAvailableFor()
{
return $this->availableFor;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add idState
*
* #param \Consolidador\PanelBundle\Entity\States $idState
* #return Offers
*/
public function addIdState(\Consolidador\PanelBundle\Entity\States $idState)
{
$this->idState[] = $idState;
return $this;
}
/**
* Remove idState
*
* #param \Consolidador\PanelBundle\Entity\States $idState
*/
public function removeIdState(\Consolidador\PanelBundle\Entity\States $idState)
{
$this->idState->removeElement($idState);
}
/**
* Get idState
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdState()
{
return $this->idState;
}
/**
* Set idState
* #param \Consolidador\PanelBundle\Entity\States $idState
*/
public function setIdState($idState)
{
$this->idState[] = $idState;
}
/**
* Cadena de texto a devolver.
* #return string
*/
public function __toString()
{
return $this->name;
}
It turns out that I select tenders belonging to a particular state, and what I do is this:
$dql = $em->createQuery("SELECT o FROM PanelBundle:Offers o WHERE o.idState = :state");
$dql->setParameter('state', $this->getUser()->getIdAgency()->getIdZone()->getIdState());
$offersState = $dql->getResult();
But I returned the following error:
[Semantical Error] line 0, col 43 near 'idState = :s': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
Does anyone has thought of something? Do you know how to consult in such institutions?
Greetings and thank you
SOLVED:
Here are the DQL queries used for offerings of a particular state and for all offers that do not belong to any (independent). There may be a more simple way, if anyone knows, you publish it.
SELECT o FROM PanelBundle:Offers o JOIN o.idState os WHERE os.id = :state
SELECT o FROM PanelBundle:Offers o WHERE o.id NOT IN (SELECT x.id FROM PanelBundle:Offers x JOIN x.idState os)
You should JOIN to states table.
$qb
->from('PanelBundle:Offers', 'o')
->select('o')
->join('PanelBundle:States', 's')
->andWhere('o.state = :state');
// ....

Sonata AdminBundle, get the parameter of an entity

I have an entity Prototype with a relation many to one with project and I want to override a function in the CRUDController.
Here is the code :
$idPrototype = $this->get('request')->get($this->admin->getIdParameter());
I get the id of the prototype, but I want the parameter 'project' ( the id of the project )
Here is my prototype entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Prototype
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\PrototypeRepository")
*/
class Prototype
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreation", type="date")
*/
private $dateCreation;
private $projet;
public function __construct()
{
$this->dateCreation = new \DateTime("now");
$this->nom = "";
$this->description = " ";
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
public function __toString()
{
return $this->getNom();
}
/**
* Set nom
*
* #param string $nom
* #return Prototype
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Set description
*
* #param string $description
* #return Prototype
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Prototype
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set projet
*
* #param \AppBundle\Entity\Projet $projet
* #return Prototype
*/
public function setProjet(\AppBundle\Entity\Projet $projet = null)
{
$this->projet = $projet;
return $this;
}
/**
* Get projet
*
* #return \AppBundle\Entity\Projet
*/
public function getProjet()
{
return $this->projet;
}
}
I've tried to use ModelManager() but I get this error "Attempted to call an undefined method named "getModelManager" of class "AppBundle\Controller\CRUDProtoController". "
I'm new with sonata and symfony and I find difficulties with it.

File Uploads with Doctrine

I am trying to upload files with Doctrine in Symfony2.
I followed all the steps in this tutorial tutorial but whene I submit my form I get no errors but the file is not uploaded and the path in the table "document" is null.
This is my entity
<?php
namespace projet\ClasseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Projet
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="projet\ClasseBundle\Entity\ProjetRepository")
* #ORM\HasLifecycleCallbacks
*/
class Projet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="idMembre", type="integer")
*/
private $idMembre;
/**
* #var integer
*
* #ORM\Column(name="idAssociation", type="integer")
*/
private $idAssociation;
/**
* #var integer
*
* #ORM\Column(name="StatutProjet", type="integer")
*/
private $StatutProjet;
/**
* #var string
*
* #ORM\Column(name="nomProjet", type="string", length=255)
*/
private $nomProjet;
/**
* #var boolean
*
* #ORM\Column(name="visibilite", type="boolean")
*/
private $visibilite;
/**
* #var string
*
* #ORM\Column(name="dateDebut", type="string", length=255)
*/
private $dateDebut;
/**
* #var string
*
* #ORM\Column(name="dateFin", type="string", length=255)
*/
private $dateFin;
/**
* #var float
*
* #ORM\Column(name="budgetActuel", type="float", nullable=true)
*/
private $budgetActuel;
/**
* #var float
*
* #ORM\Column(name="budget", type="float")
*/
private $budget;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="ficheProjet", type="string", length=255, nullable=true)
*/
private $ficheProjet;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set idMembre
*
* #param integer $idMembre
* #return Projet
*/
public function setIdMembre($idMembre)
{
$this->idMembre = $idMembre;
return $this;
}
/**
* Get idMembre
*
* #return integer
*/
public function getIdMembre()
{
return $this->idMembre;
}
/**
* Set idAssociation
*
* #param integer $idAssociation
* #return Projet
*/
public function setIdAssociation($idAssociation)
{
$this->idAssociation = $idAssociation;
return $this;
}
/**
* Get idAssociation
*
* #return integer
*/
public function getIdAssociation()
{
return $this->idAssociation;
}
/**
* Set StatutProjet
*
* #param integer $StatutProjet
* #return Tache
*/
public function setStatutProjet($StatutProjet)
{
$this->StatutProjet = $StatutProjet;
return $this;
}
/**
* Get StatutProjet
*
* #return integer
*/
public function getStatutProjet()
{
return $this->StatutProjet;
}
/**
* Set nomProjet
*
* #param string $nomProjet
* #return Projet
*/
public function setNomProjet($nomProjet)
{
$this->nomProjet = $nomProjet;
return $this;
}
/**
* Get nomProjet
*
* #return string
*/
public function getNomProjet()
{
return $this->nomProjet;
}
/**
* Set visibilite
*
* #param boolean $visibilite
* #return Projet
*/
public function setVisibilite($visibilite)
{
$this->visibilite = $visibilite;
return $this;
}
/**
* Get visibilite
*
* #return boolean
*/
public function getVisibilite()
{
return $this->visibilite;
}
/**
* Set dateDebut
*
* #param string $dateDebut
* #return Projet
*/
public function setDateDebut($dateDebut)
{
$this->dateDebut = $dateDebut;
return $this;
}
/**
* Get dateDebut
*
* #return string
*/
public function getDateDebut()
{
return $this->dateDebut;
}
/**
* Set dateFin
*
* #param string $dateFin
* #return Projet
*/
public function setDateFin($dateFin)
{
$this->dateFin = $dateFin;
return $this;
}
/**
* Get dateFin
*
* #return string
*/
public function getDateFin()
{
return $this->dateFin;
}
/**
* Set budget
*
* #param float $budget
* #return Projet
*/
public function setBudget($budget)
{
$this->budget = $budget;
return $this;
}
/**
* Get budget
*
* #return float
*/
public function getBudget()
{
return $this->budget;
}
/**
* Set budgetActuel
*
* #param float $budgetActuel
* #return Projet
*/
public function setBudgetActuel($budgetActuel)
{
$this->budgetActuel = $budgetActuel;
return $this;
}
/**
* Get budgetActuel
*
* #return float
*/
public function getBudgetActuel()
{
return $this->budgetActuel;
}
/**
* Set description
*
* #param string $description
* #return Projet
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set ficheProjet
*
* #param string $ficheProjet
* #return Projet
*/
public function setFicheProjet($ficheProjet)
{
$this->ficheProjet = $ficheProjet;
return $this;
}
/**
* Get ficheProjet
*
* #return string
*/
public function getFicheProjet()
{
return $this->ficheProjet;
}
public function getAbsolutePath()
{
return null === $this->ficheProjet ? null : $this->getUploadRootDir().'/'.$this->ficheProjet;
}
public function getWebPath()
{
return null === $this->ficheProjet ? null : $this->getUploadDir().'/'.$this->ficheProjet;
}
protected function getUploadRootDir()
{
// le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
// le document/image dans la vue.
return 'uploads/documents';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// faites ce que vous voulez pour générer un nom unique
$this->ficheProjet = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
// s'il y a une erreur lors du déplacement du fichier, une exception
// va automatiquement être lancée par la méthode move(). Cela va empêcher
// proprement l'entité d'être persistée dans la base de données si
// erreur il y a
$this->file->move($this->getUploadRootDir(), $this->ficheProjet);
unset($this->file);
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
NB : I mean ficheProjet by path.
Anny suggestion ? And thanks.
You should try to use Doctrine Uploadable Extension
You have to install the StofDoctrineExtensionBundle
After you should be able to add on your entity :
namespace My\Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* MyEntity
*
* #ORM\Table(name="my_entity")
* #ORM\Entity()
* #Gedmo\Uploadable(
* path="uploads/my_entity",
* allowOverwrite=true,
* allowedTypes="image/jpeg,image/pjpeg,image/png,image/x-png"
* )
*/
class MyEntity
{
//...
/**
* #var string
*
* #ORM\Column(name="picture", type="string", length=255, nullable=true)
* #Gedmo\UploadableFilePath
* #Assert\File(
* mimeTypes={"image/jpeg", "image/pjpeg", "image/png", "image/x-png"}
* )
*/
private $picture;
//...
}
Don't forget to create the upload folder and set right permissions:
mkdir -p web/uploads/my_entity
chmod -R 777 web/uploads

Resources