I'm doing an AdvertPlatform with Symfony 2.5 and PHP 5.3.
I want to add a feature that is : when a user see(by clicking on it) an advert, we can see a text "Seen by : {{username}}".
I started add a new Entity nammed AdvertReader with a relation OneToMany between Advert and AdvertReader:
Advert.php:
/**
* Advert
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Society\PerfclientBundle\Entity\AdvertRepository")
* #ORM\HasLifecycleCallbacks()
* #UniqueEntity(fields="title", message="Une annonce existe déjà avec ce titre.")
*/
class Advert
{
public function __construct()
{
$this->date = new \Datetime();
}
/**
*
* #ORM\OneToMany(targetEntity="Society\PerfclientBundle\Entity\AdvertReader", mappedBy="advert", cascade={"persist"})
*/
private $readers;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255, unique=true)
*
* #Assert\Length(min=10, minMessage="Le titre de l'annonce doit faire au moins {{ limit }} caractères.")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=255)
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
* #Assert\Length(min=10, minMessage="Le contenu de l'annonce doit faire au moins {{ limit }} caractères.")
*/
private $content;
/**
* #ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
private $updatedAt;`
AdvertReader.php :
/**
* AdvertReader
*
* #ORM\Table()
* #ORM\Entity
*/
class AdvertReader
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Society\PerfclientBundle\Entity\Advert", inversedBy="readers")
* #ORM\JoinColumn(name="advert_id", referencedColumnName="id")
*/
private $advert;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
*/
private $username;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set advert
*
* #param integer $advert
* #return AdvertReader
*/
public function setAdvert($advert)
{
$this->advert = $advert;
return $this;
}
/**
* Get advert
*
* #return integer
*/
public function getAdvert()
{
return $this->advert;
}
/**
* Set username
*
* #param string $username
* #return AdvertReader
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
And my viewAction()
/**
* #param $id
* #return Response
*/
public function viewAction($id)
{
// On récupère le repository
$repository = $this->getDoctrine()
->getManager()
->getRepository('SocietyPerfclientBundle:Advert')
;
$advert = $repository->find($id);
if (null === $advert) {
throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
}
$securityContext = $this->container->get('security.context');
$user = $securityContext->getToken()->getUser();
if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->createQueryBuilder();
$query = $queryBuilder->select('count(ar.id)')
->from('SocietyPerfclientBundle:AdvertReader', 'ar')
->where('ar.advert = :advert')
->andWhere('ar.username = :username')
->setParameter('advert', $advert->getId())
->setParameter('username', $user->getUsername())
->getQuery();
$advertReaderCount = $query->getSingleScalarResult();
if ($advertReaderCount <= 0) {
// l'utilisateur lis pour la 1er fois
$advertReader = new AdvertReader;
$advertReader->setAdvert($advert->getId());
$advertReader->setUpdatedAt(new \DateTime);
$advertReader->setUsername($user->getUsername());
$advertReader->setCreatedAt(new \DateTime);
$em->persist($advertReader);
$em->flush();
}
}
return $this->render('SocietyPerfclientBundle:Default:view.html.twig', array(
'advert' => $advert,
));
}
doctrine:schema:validate -> [Mapping] OK [Database] OK
Error500 ORM Exception : Found entity of type on association Society\PerfclientBundle\Entity\AdvertReader#advert, but expecting Society\PerfclientBundle\Entity\Advert
Stack Trace Profiler :
UnitOfWork ->computeAssociationChanges (array('fieldName' => 'advert', 'joinColumns' => array(array('name' => 'advert_id', 'unique' => false, 'nullable' => true, 'onDelete' => null, 'columnDefinition' => null, 'referencedColumnName' => 'id')), 'cascade' => array(), 'inversedBy' => 'readers', 'targetEntity' => 'Society\PerfclientBundle\Entity\Advert', 'fetch' => '2', 'type' => '2', 'mappedBy' => null, 'isOwningSide' => true, 'sourceEntity' => 'Society\PerfclientBundle\Entity\AdvertReader', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'sourceToTargetKeyColumns' => array('advert_id' => 'id'), 'joinColumnFieldNames' => array('advert_id' => 'advert_id'), 'targetToSourceKeyColumns' => array('id' => 'advert_id'), 'orphanRemoval' => false), '26')
What's wrong with my entity relation ?
Please help me :)
I think the problem comes from this code piece of code
$advertReader->setAdvert($advert->getId());
Try this instead:
$advertReader->setAdvert($advert);
Doctrine is expecting an object on that relation and instead you pass some integer.
Hope this helps. Happy coding
Alexandru Cosoi
Related
I have many entities with it relations and due to optimize REST calls to select only this fields that I need actually also with entities relations.
So, I have entity like this:
/**
* #ORM\Entity(repositoryClass="App\Repository\DocumentRepository")
* #ORM\Table(name="document_types")
*/
class DocumentType
{
use RestDefaultsTrait;
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
* #Serializer\Groups({"main-document-type"})
*/
private $id;
/**
* #ORM\Column(type="string", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $slug;
/**
* #ORM\Column(type="string", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $symbol;
/**
* #ORM\Column(type="string")
* #Serializer\Groups({"main-document-type"})
*/
private $name;
/**
* #ORM\Column(type="string", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $description;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $canBeGenerated;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $inEmployer;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $inWorker;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $inAll;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $isAnnex;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*
*
*/
private $isAttachment;
/**
* #ORM\ManyToOne(targetEntity="DocumentType", inversedBy="childDocuments")
* #Serializer\Groups({"main-document-type"})
*/
private $parentDocument;
/**
* #ORM\OneToMany(targetEntity="DocumentType", mappedBy="parentDocument")
* #Serializer\Groups({"main-document-type"})
*
*/
private $childDocuments;
/**
* #ORM\Column(type="string", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $annexNumberStart;
/**
* #ORM\ManyToOne(targetEntity="ProfessionGroup", inversedBy="documentTypes")
* #Serializer\Groups({"main-document-type"})
*/
private $professionGroup;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $isNumbering;
/**
* #ORM\Column(type="array", nullable=true)
*/
private $employmentGroup = [];
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $canNumberBeSuggested = false;
/**
* #ORM\Column(type="boolean", nullable=true)
* #Serializer\Groups({"main-document-type"})
*/
private $canBeEdited = false;
}
And in entity repository i want to do something like this:
public function getDocuments( $filterData )
{
$select = [
// 'id' => 'id',
'slug' => 'slug',
'name' => 'name',
'isAnnex' => 'is_annex',
'canNumberBeSuggested' => 'can_number_be_suggested',
'canBeEdited' => 'can_be_edited',
];
$childDocumentsSelect = [
'id' => 'id',
'name' => 'name',
];
$qb = $this->createQueryBuilder( 'document' )
->where( 'document.canBeGenerated = 1' )
;
$qb->select( 'document.id AS id' );
foreach ( $select as $selectField => $selectValue )
{
$qb->addSelect( sprintf( 'document.%s AS %s', $selectField, $selectValue ) );
}
$qb->join( 'document.childDocuments', 'childDocuments' );
foreach ( $childDocumentsSelect as $selectField => $selectValue )
{
$qb->addSelect( sprintf( 'childDocuments.%s AS %s', $selectField, $selectValue ) );
}
return $qb->getQuery()->getResult();
}
with in results I want to recieve base fields from $select array and an array of child documents with selected fields in $childDocumentsSelect in this example only id and name
Is even possible? Sometimes my entities have 3 associations sometimes none. At this moment I'm using serializer but want to optimalize this
Try my example, I think this is what you need.
$qb = $this->createQueryBuilder( 'document' );
$qb->select([
'document.slug',
'document.name',
'document.isAnnex',
'document.canNumberBeSuggested',
'document.canBeEdited',
'childDocument.id',
'childDocument.name'
])
->leftJoin('documnet.childDocuments', 'childDocument')
->where('document.canBeGenerated = 1');
$queryResult = $qb->getQuery()->getResult();
$items = [];
foreach($queryResult as $item) {
$id = $item['id'];
if (!isset($items[$id])) {
$items[$id]['id'] = $id;
}
$items[$id]['child'][] = [
'slug' => $item['name']
];
}
var_dump($items);
I have a form which save queries. This is organized in the way of a people who ask is saved also this create a threat where is saving the id_question and emailperson. The issue is that the same person does another question. Logically, this report a primary key error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'drj00003#ujaen.es' for key 'PRIMARY'
How do I fix it? In the constructor of class I cannot check if this exists and all registers are generated automatically in cascade without form.
It should be easy but I can't solve this.
class HiloType extends AbstractType{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('consultanteemail', new ConsultanteType(), array ('label' => false))
->add('personalemail', 'entity', array(
'label' => 'Personal de Soporte',
'class' => 'GuiasDocentes\AppBundle\Entity\Personal',
'property' => 'Enunciado',
'by_reference' => 'false',
'query_builder' => function(PersonalRepository $pr) {
$query= $pr->createQueryBuilder('u')
;
return $query;
},
'empty_value' => 'Elige un perfil de consulta:',
))
;
}
...
class Hilo{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \GuiasDocentes\AppBundle\Entity\Personal
*
* #ORM\ManyToOne(targetEntity="Personal", inversedBy="hilos", cascade ={"ALL"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="personalEmail", referencedColumnName="email")
* })
*/
private $personalemail;
/**
* #var \GuiasDocentes\AppBundle\Entity\Consultante
*
* #ORM\ManyToOne(targetEntity="Consultante", inversedBy="hilos", cascade ={"ALL"} )
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="consultanteEmail", referencedColumnName="email")
* })
*/
private $consultanteemail;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Consulta", mappedBy="hiloid")
* #Assert\Valid()
*/
private $consultas;
public function __construct(){
$this->consultas = new ArrayCollection();
}
public function setConsultas (Consulta $consulta){
$this->hilos[]=$consulta;
}
public function addConsulta (\GuiasDocentes\AppBundle\Entity\Consulta $consulta){
$this->hilos[] = $consulta;
}
/* End customized code */
...
class Consultante{
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=50, nullable=false)
* #ORM\Id
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=30, nullable=true)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="apellidos", type="string", length=50, nullable=true)
*/
private $apellidos;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Hilo", mappedBy="consultanteemail")
* #Assert\Valid()
*/
private $hilos;
public function __construct(){
$this->hilos = new ArrayCollection();
}
public function setHilos (Hilo $hilo){
$this->hilos[]=$hilo;
}
public function addHilo (\GuiasDocentes\AppBundle\Entity\Hilo $hilo){
$this->hilos[] = $hilo;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/* End customize code */
...
public function contactoAction (Request $request){
$session = $request->getSession();
$perfil = $session->get('perfil');
$consultaHasAsignatura = new ConsultaHasAsignatura();
$form = $this->createForm(new ConsultaHasAsignaturaType(), $consultaHasAsignatura);
if ($request->isMethod('POST')){
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($consultaHasAsignatura);
$em->flush();
return $this->redirectToRoute('guias_docentes_app_homepage');
}
}
return $this->render('GuiasDocentesAppBundle:FAQ:contacto.html.twig', array('perfil'=>$perfil,
'form' => $form->createView()
));
}
I'm trying to get my form working since two days.
I'm reading the chapter "Forms" in the Symfony book up and down but i don't know what I'm doing wrong.
This is my Entity class:
/**
* Homecontent
*
* #ORM\Table(name="homecontent", indexes={#ORM\Index(name="id_idx", columns={"author_id"})})
* #ORM\Entity()
*/
class Homecontent
{
/**
* #var integer
*
* #ORM\Column(name="home_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $homeId;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="title", type="text", nullable=false)
*
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* #var string
*
* #ORM\Column(name="picture_path", type="text", nullable=false)
*/
private $picturePath;
/**
* #var \Contentuser
*
* #ORM\ManyToOne(targetEntity="Contentuser")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="author_id", referencedColumnName="content_user_id")
* })
*/
private $author;
This is my controller:
/**
* #param $request
* #return \Symfony\Component\HttpFoundation\Response
* #Route("/content/insert")
*/
public function indexAction(Request $request)
{
$content = new HomecontentType();
$form = $this->createForm(HomecontentType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()
->getManager();
$em->persist($content);
$em->flush();
return $this->redirectToRoute('worked check index');
}
return $this->render('Form/ContentForm.html.twig', array('form' => $form->createView()));
And this is my Form Class:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('content')
->add('picturePath')
->add('date',DateTimeType::class)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Homecontent'
));
}
}
I use twig for the rendering and it's working, but when i want to submit it i get an error
The class 'AppBundle\Form\HomecontentType' was not found in the chain configured namespaces AppBundle\Entity
I'm sorry for the long code section.
Thanks in advance!
At the beginning of the indexAction you have error, the correct code is:
$content = new Homecontent();
$form = $this->createForm(HomecontentType::class, $content);
i have an error :
Catchable Fatal Error: Object of class ParcAutoBundle\Entity\Car could not be converted to string
my class of maintenance is :
<?php
namespace AutoEcole\ParcAutoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Maintenance
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AutoEcole\ParcAutoBundle\Entity\MaintenanceRepository")
*/
class Maintenance {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="datemaintenance", type="string", length=255)
*/
private $datemaintenance;
/**
* #var integer
*
* #ORM\Column(name="mileage", type="bigint")
*/
private $mileage;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set datemaintenance
*
* #param string $datemaintenance
* #return Maintenance
*/
public function setDatemaintenance($datemaintenance) {
$this->datemaintenance = $datemaintenance;
return $this;
}
/**
* Get datemaintenance
*
* #return string
*/
public function getDatemaintenance() {
return $this->datemaintenance;
}
/**
* Set mileage
*
* #param integer $mileage
* #return Maintenance
*/
public function setMileage($mileage) {
$this->mileage = $mileage;
return $this;
}
/**
* Get mileage
*
* #return integer
*/
public function getMileage() {
return $this->mileage;
}
/**
* Set description
*
* #param string $description
* #return Maintenance
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* #ORM\ManyToOne(targetEntity="\AutoEcole\ParcAutoBundle\Entity\Car")
* #ORM\JoinColumn(nullable=false)
*/
private $car;
/**
* Set car
*
* #param \AutoEcole\ParcAutoBundle\Entity\Car $car
* #return Maintenance
*/
public function setCar(\AutoEcole\ParcAutoBundle\Entity\Car $car = null) {
$this->car = $car;
return $this;
}
/**
* Get car
*
* #return \AutoEcole\ParcAutoBundle\Entity\Car
*/
public function getCar() {
return $this->car;
}
}
my function in controller is :
if you want the MaintenanceType tell me
public function addcarmaintenanceAction($id, Request $request) {
//User connecté
$user = $this->getUser();
$maintenance = new Maintenance();
$car = $this->getDoctrine()->getManager()->getRepository('ParcAutoBundle:Car')->find($id);
//dump($car);
//die();
//Création du formulaire
$form = $this->createForm(new MaintenanceType());
$form->handleRequest($request);
if ($form->isValid()) {
//Récupération des données du formulaire de l'ajout du voiture
$datemaintenance = $form['datemaintenance']->getData();
$mileage = $form['mileage']->getData();
$description = $form['description']->getData();
//Préparation de l'objet pour le persister et faire flush() ensuite
$maintenance->setDatemaintenance($datemaintenance);
$maintenance->setMileage($mileage);
$maintenance->setDescription($description);
$maintenance->setCar($id);
//Entity Manager
$em = $this->getDoctrine()->getManager();
$em->persist($maintenance);
$em->flush();
$message = "style=display:block;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'form' => $form->createView(),
'user' => $user,
'message' => $message,
'car' => $car
));
}
$message = "style=display:none;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'user' => $user,
'form' => $form->createView(),
'message' => $message,
'car' => $car
));
}
the problem is solved , i putted the __toString() in the Car Class
public function __toString() {
return (string) $this->getRegistrationnumber();
}
In you ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig template, try to display a property of car, not car directly:
{{ car.model }} // it's an exemple property
// instead of
{{ car }}
Here I am on a project for my studies and I use symfony fosUser and sonata, I have a Book entity that I administer with sonata.
The problem is that I want to give an user to a book, but it becomes complicated when I want to find in my field user only the user whose role ROLE_MyRole, I search on forums for several hours without finding.
I'm sorry for my incompetence I learn symfony recently and does not yet have enough experience.
This is my BookAdmin
class BookAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
static $options = array();
$currentBook = $this->getSubject();
if (null !== $currentBook->getFileName())
$options = array(
'required' => false,
'help' => 'getWebPath().'">Download File : '.$currentBook->getFileName().'',
);
$formMapper
->add('title', null, array('label' => 'Titre : '))
->add('summary', null, array('label' => 'Résumé : '))
->add('category', null, array('label' => 'Catégorie : '))
->add('readers', null, array('label' => 'Lecteur(s) : '))
->add('file', 'file', $options)
;
}
And this is my Book entity with readers field
class Book
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
/**
* #var string
*
* #ORM\Column(name="summary", type="text")
*/
protected $summary;
/**
* #Assert\File(
* mimeTypes={"application/pdf", "application/x-pdf"},
* mimeTypesMessage="Only PDF"
* )
*/
protected $file;
/**
* #var string
*
* #ORM\Column(name="file_path", type="string", length=255)
*/
protected $fileName;
/**
* #var \DateTime
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="created_at", type="datetime")
*/
protected $createdAt;
/**
* #var \DateTime
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(name="updated_at", type="datetime")
*/
protected $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="enabled", type="boolean", nullable=true)
*/
protected $enabled;
/**
* #var bool
*
* #ORM\Column(name="received_by_reader", type="boolean", nullable=true)
*/
protected $receivedByReader;
/**
* #var bool
*
* #ORM\Column(name="download_by_reader", type="boolean", nullable=true)
*/
protected $downloadByReader;
/**
* #var bool
*
* #ORM\Column(name="send_by_reader", type="boolean", nullable=true)
*/
protected $sendByReader;
/**
* #var bool
*
* #ORM\Column(name="reader_validation", type="boolean", nullable=true)
*/
protected $readerValidation;
/**
* #var bool
*
* #ORM\Column(name="edited", type="boolean", nullable=true)
*/
protected $edited;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
*/
protected $author;
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User", cascade={"persist"})
*/
protected $readers;
Thanks You
You can do something like this in your admin class:
$formMapper
->add('readers', null, array(
'label' => 'Lecteur(s) : ',
'code' => 'getReadersWithMyRole'
))
and define in your User entity the following method:
/**
* Returns readers with "ROLE_MyRole" role
*
* #return array
*/
public function getReadersWithMyRole()
{
$result = array();
foreach ($this->getReaders() as $reader) {
if ($reader->hasRole('ROLE_MyRole')) {
$result[] = $reader;
}
}
return $result;
}
Hope it helps.
it doesn't work too but we have find a solution, we can do that like this :
->add('reader', null, array(
'class' => 'ApplicationSonataUserBundle:User',
'label' => 'Lecteur : ',
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('u');
$qb->where($qb->expr()->like('u.roles', $qb->expr()->literal('%ROLE_READER%')));
return $qb;
}))
if it can help someone