Doctrine cascade persistence never check if object exists Symfony 2 - symfony

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

Related

Error : Could not determine access type for property "articlesCategories" in class "Articles"

I am using Symfony 3.4.7 . I work with 3 linked entites, Article, Categorie and ArticlesCategories. ArticlesCategories is the relation table.
I would like to add and edit articles. I wish I could Add / Edit articles, given that an article may have several Categories and vice versa. I have attributes specific to the relationship in the relation table , that's why I created the relation entity.
This is the code of an Articles :
/**
* Articles
*
* #ORM\Table(name="articles")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ArticlesRepository")
*/
class Articles
{
/**
* #var string
*
* #ORM\Column(name="code_article", type="string", length=10)
* #ORM\Id
*/
private $codeArticle;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var ArticlesCategories
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\ArticlesCategories", mappedBy="codeArticle")
*/
private $articlesCategories;
// getters et setters normaux
...
/**
* Add articlesCategorie
*
* #param ArticlesCategories $articleCategorie
*
* #return Articles
*/
public function addArticlesCategorie(ArticlesCategories $articleCategorie){
$this->articlesCategories[] = $articleCategorie;
$articleCategorie->setCodeArticle($this);
return $this;
}
/**
* remove articlesCategorie
*
* #param ArticlesCategories $articlesCategorie
*/
public function removeArticlesCategorie(ArticlesCategories $articlesCategorie){
$this->articlesCategories->removeElement($articlesCategorie);
}
/**
* Get articlesCategories
*
* #return Collection
*/
public function getArticlesCategories(){
return $this->articlesCategories;
}
public function __toString()
{
return $this->codeArticle;
}
public function __construct()
{
$this->articlesCategories = new ArrayCollection();
}
This is the code of the relation ArticlesCategories:
/**
* ArticlesCategories
*
* #ORM\Table(name="articles_categories")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ArticlesCategoriesRepository")
*/
class ArticlesCategories
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Articles", inversedBy="articlesCategories")
* #ORM\JoinColumn(referencedColumnName="code_article", nullable=false)
*/
private $codeArticle;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Categories")
* #ORM\JoinColumn(referencedColumnName="reference", nullable=false)
*/
private $codeCategorie;
/**
* #var string
*
* #ORM\Column(name="critere_rech_1", type="string", length=45, nullable=true)
*/
private $critereRech1;
/**
* #var string
*
* #ORM\Column(name="critere_rech_2", type="string", length=45, nullable=true)
*/
private $critereRech2;
And my entite Categories has nothing specific.
I generate automatically the crud of my entitie Articles, then I edit the class ArticlesType to have all attributes of my relation ArticlesCategories who are displays. To do this edition I use CollectionType.
This the code of my Form ArticlesType :
class ArticlesType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('codeArticle')
->add('description')
->add('ecotaxe')
->add('qteMaxCde')
->add('publication')
->add('designation')
->add('taxonomie')
->add('referenceStock')
->add('articleRegroupement')
->add('articleAssocie1')
->add('articleAssocie2')
->add('articleAssocie3')
->add('seuilDegressif')
->add('tauxDegressif')
->add('articlesCategories', CollectionType::class, array(
'entry_type' => ArticlesCategoriesType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
'label' => 'test',
'attr' => array('class' => 'collection-articlesCategories'),
'auto_initialize' => true
));
}
public function getName(){
return 'Articles';
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Articles'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_articles';
}
}
When I go on the Article edition page that was generates by Symfony, I get the right display.
Edition page
But When I click on the button "Edit", I get this error : Could not determine access type for property "articlesCategories" in class "AppBundle\Entity\Articles".
I don't see where is my mistake.
I hope I am clear.
Thank you for help.
Try putting the following:
public function setArticlesCategories(...) {
...
}

Symfony2 OneToMany relation

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

Creating Forms with Symfony and Doctrine

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

Assign and remove items from one category

Assign many items to one category - OneToMany Relation
and
Symfony form not saving entity with ManyToMany relation
Based on the two questions above I have an list with many checkboxes for all items. So it does not make any sense to have 2 Routes/Methods: One for assign and another for removing the items. To make it logically correct, assign items and remove items have to be in one method - this method down under is only working for assigning and not for removing one ore more items. In a real application assign and remove items in one step is the only way it makes sense (because of the checkboxes).
/**
* Assign items to category and remove items from the list
*
* #Route("/{id}/assign", name="category_assign")
* #Template("CheckoutItemBundle:Category:assign.html.twig")
* #param Request $request
* #param $id
* #return array|\Symfony\Component\HttpFoundation\RedirectResponse
*/
public function assignAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('CheckoutItemBundle:Category')->find($id);
if (!$entity)
{
throw $this->createNotFoundException('Unable to find Category entity.');
}
$tokenStorage = $this->container->get('security.token_storage');
$form = $this->createForm(new CategoryItemType($tokenStorage), $entity, array(
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Save'));
$form->handleRequest($request);
if ($form->isValid())
{
$data = $form->getData();
foreach($data->getItems() as $item)
{
$item->setCategory($entity);
$em->persist($item);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('category'));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
Form:
<?php
namespace Checkout\Bundle\ItemBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityRepository;
class CategoryItemType extends AbstractType
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$currentUser = $this->tokenStorage->getToken()->getUser();
$builder
->add('items', 'entity', array(
'label' => 'Items',
'required' => false,
'class' => 'CheckoutItemBundle:Item',
'property' => 'name',
'expanded' => true,
'multiple' => true,
'query_builder' => function (EntityRepository $er) use ($currentUser) {
return $er->createQueryBuilder('c')
->where('c.user = :user')
->setParameter('user', $currentUser);
},
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Checkout\Bundle\ItemBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'checkout_bundle_itembundle_category_items';
}
}
Entity Category:
class Category
{
/**
* #var integer
*
* #ORM\Column(type="guid")
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Checkout\Bundle\ItemBundle\Entity\Item", mappedBy="category", cascade={"persist", "remove"})
**/
private $items;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user;
/**
* Get id
*
* #return integer
*/
Here the complete one: http://laravel.io/bin/bEEr5 (It's just to long, to paste it here.)
Entity Item:
class Item
{
/**
* #var integer
*
* #ORM\Column(type="guid")
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description = null;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Checkout\Bundle\ItemBundle\Entity\ItemCharakter", mappedBy="item", cascade={"persist", "remove"})
**/
private $itemCharakters;
/**
* #ORM\ManyToOne(targetEntity="Checkout\Bundle\ItemBundle\Entity\Category", inversedBy="items")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
**/
private $category;
/**
* #ORM\ManyToMany(targetEntity="Checkout\Bundle\ItemBundle\Entity\Tax", inversedBy="items")
* #ORM\JoinTable(name="Items_Taxes")
*/
private $taxes;
/**
* #ORM\ManyToMany(targetEntity="Checkout\Bundle\ItemBundle\Entity\Modifier", inversedBy="items")
* #ORM\JoinTable(name="Items_Modifiers")
*/
private $modifiers;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user;
/**
* #var \DateTime $created_at
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created_at;
/**
* #var \DateTime $updated_at
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated_at;
the complete entity: http://laravel.io/bin/XyyxB
.
First scenario:
Assign Items to Category:
[ ] Item 1
[ ] Item 2
assign all ====>
Assign Items to Category:
[X] Item 1
[X] Item 2
Second:
Assign Items to Category:
[ ] Item 1 // Remove this item 1, after it was assign
[X] Item 2 // Stay assigned
I'm not on the owning side here. I'm using Symfony 2.6.7. In this example it is an OneToMany Relation, but in the future I need it also for ManytoMany Relation.
Any idea, how this is possible for OneToMany and ManyToMany, when I'm not on the owning side? :-)
I also followed this guide for the adding items part: http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations - may it help to clarify.

Show only user with a specific role in FormFields sonata

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

Resources