Controller, repo and twig print array (Symfony3) - symfony

I need to print domains of a single user
ENTITY (here is the entity code)
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Domini
*
* #ORM\Table(name="domini")
* #ORM\Entity(repositoryClass="AppBundle\Repository\DominiRepository")
*/
class Domini
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="id_user", type="integer")
*/
private $idUser;
/**
* #var string
*
* #ORM\Column(name="dominio", type="string", length=100, unique=true)
*/
private $dominio;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set idUser
*
* #param integer $idUser
*
* #return Domini
*/
public function setIdUser($idUser)
{
$this->idUser = $idUser;
return $this;
}
/**
* Get idUser
*
* #return int
*/
public function getIdUser()
{
return $this->idUser;
}
/**
* Set dominio
*
* #param string $dominio
*
* #return Domini
*/
public function setDominio($dominio)
{
$this->dominio = $dominio;
return $this;
}
/**
* Get dominio
*
* #return string
*/
public function getDominio()
{
return $this->dominio;
}
}
REPOSITORY (here is the Repo code)
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Domini;
use Doctrine\ORM\EntityRepository;
class DominiRepository extends \Doctrine\ORM\EntityRepository
{
/**
* #return dominio[]
*/
public function findAllPublishedOrderedBySize()
{
$query = 'SELECT dominio FROM AppBundle:Domini dominio';
$mydomain = $this->getEntityManager()->createQuery($query);
return $mydomain->execute();
}
}
CONTROLLER
<?php
// src/AppBundle/Controller/DominiController.php
namespace AppBundle\Controller;
use AppBundle\Entity\Domini;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManagerInterface;
class DominiController extends Controller
{
/**
* #Route("/admin/domini")
*/
public function dominiAction()
{
$title = "ADMIN";
$nome_utente = $this->getUser();
$user = $this->getUser()->getId();
$em = $this->getDoctrine()->getManager();
$dominilist = $em->getRepository('AppBundle:Domini')
->findAllPublishedOrderedBySize();
return $this->render('admin/domini.html.twig', [
'title' => $title,
'nome_utente' => $nome_utente,
'user' => $user,
'dominilist' => $dominilist,
]);
}
}
TWIG
<h1>{{ title }}</h1>
<h2>Benvenuto: {{ nome_utente }}</h2>
<h3>USER ID:{{ user }}</h3>
<ul>
{% for item in dominilist %}
<li>{{ item.dominio }}</li>
{% endfor %}
</ul>
MYSQL TABLE
table name: domini
fields: id, id_user, dominio
Now all works fine but 'dominilist' => $dominilist doesn't work. Dominio is the domain name saved under "dominio". Why?
IF i try to cicle this field it doesn't work.

If you want to select all the data stored in that table, you can use a quick and handy method directly in your controller
# Controller
$dominilist = $em->getRepository('AppBundle:Domini')
->findAll();
Or you can find domini by id in the controller too:
# Controller
$user = $this->getUser()->getId();
$dominilist = $em->getRepository('AppBundle:Domini')->findBy(['id'=>$user]);
And only if you want to have a more complex query, then you can create q method in the repository. As that "I need to print domains of a single user"
# Repository
public function findAllPublishedOrderedBySize($id)
{
$qb = $this->createQueryBuilder('d');
$qb
->select('d.dominio')
->where('d.id = :id')
->setParameter('id', $id)
;
return $qb->getQuery()->getResult();
}
# Controller
$user = $this->getUser()->getId();
$domini = $em->getRepository('AppBundle:Domini')
->findAllPublishedOrderedBySize($user);
Anyway, those type of queries are small, and you can create them in the controller, as I showed you above.

Related

Query Builder in repository: Error: Class 'AppBundle\Entity\' is not defined

I try to make a custom deletion logic via a custom repository:
namespace AppBundle\Repository;
use AppBundle\Entity\ContactEmail;
class ContactEmailRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Remove an email from the database
* #param String $email
*/
public function deleteEmail($email)
{
$em=$this->getEntityManager();
$queryBuilder = $em->createQueryBuilder();
$queryBuilder->delete('AppBundle::ContactEmail','c')
->where('c.email=:email')
->setParameter('email',$email);
$query=$queryBuilder->getQuery();
$p = $query->execute();
return $p;
}
}
And I test it via a functional test:
namespace Tests\AppBundle\Repository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use AppBundle\Entity\ContactEmail;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\Tools\SchemaTool;
Use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use AppBundle\DataFixtures\ContactEmailDataFixture;
class ContactEmailTest extends KernelTestCase
{
/**
* #var \Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
* {#inheritDoc}
*/
protected function setUp()
{
$kernel = self::bootKernel();
$this->entityManager = $kernel->getContainer()
->get('doctrine')
->getManager();
//In case leftover entries exist
$schemaTool = new SchemaTool($this->entityManager);
$metadata = $this->entityManager->getMetadataFactory()->getAllMetadata();
// Drop and recreate tables for all entities
$schemaTool->dropSchema($metadata);
$schemaTool->createSchema($metadata);
}
/**
* Testing whether a preloaded email will get deleted
*/
public function testDeletion()
{
$fixture = new ContactEmailDataFixture();
$fixture->load($this->entityManager);
/**
* #var Appbundle\Repository\ContactEmailRepository
*/
$repository=$this->entityManager->getRepository(ContactEmail::class);
$emailToDelete='jdoe#example.com';
$repository->deleteEmail($emailToDelete);
$emailSearched=$repository->findOneBy(['email'=>$emailToDelete]);
$this->assertEmpty($emailSearched);
}
}
My entity is the following:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* ContactEmail
*
* #ORM\Table(name="contact_email")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ContactEmailRepository")
* #UniqueEntity("email")
*/
class ContactEmail
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var String
* #ORM\Column(name="email",type="string",unique=true)
* #Assert\Email( message = "The email '{{ value }}' is not a valid email.")
*/
private $email;
/**
* #ORM\Column(name="date", type="datetime")
*/
private $createdAt;
public function __construct()
{
$this->createdAt=new \DateTime("now", new \DateTimeZone("UTC"));
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param String $email
* #return ContactEmail
*/
public function setEmail($email){
$this->email=$email;
return $this;
}
/**
* #return String
*/
public function getEmail(){
return $this->email;
}
public function getCreatedAt()
{
return $this->createdAt;
}
}
And I use the following DataFixture:
namespace AppBundle\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\ContactEmail;
class ContactEmailDataFixture extends Fixture
{
public function load(ObjectManager $manager)
{
$emails=['jdoe#example.com','example#gmail.com','user1#example.com'];
foreach($emails as $email){
$emailEntityInstance=new ContactEmail();
$emailEntityInstance->setEmail($email);
$manager->persist($emailEntityInstance);
$manager->flush();
}
}
}
The problem is that I get the following error when I run the test:
Doctrine\ORM\Query\QueryException: [Semantical Error] line 0, col 7 near 'AppBundle::ContactEmail': Error: Class 'AppBundle\Entity\' is not defined.
So I want to know what I did wrong on the query syntax?
In a class that extends Doctrine\ORM\EntityRepository and that is referenced in the entity's #Entity docblock annotation's repositoryClass attribute, you can get a query builder like this:
$queryBuilder = $this->createQueryBuilder('c')
->where('c.email=:email')
->setParameter('email',$email);

Symfony Doctrine return empty values

I use Symfony doctrine to set and get data from my MySQL database. I can push new data without any problem but when I try to get them with a findAll for exemple, I get an array with the good length but nothing in.
Here's my controller:
namespace KGN\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;
use KGN\CoreBundle\Entity\Appointment;
use KGN\CoreBundle\Entity\Testy;
class AdminController extends Controller
{
public function indexAction()
{
return $this->render('KGNCoreBundle:Admin:index.html.twig');
}
public function aptAction()
{
$rep = $this->getDoctrine()
->getRepository('KGNCoreBundle:Testy');
$testy = $rep->findAll();
// return new Response('This is for show : '. count($testy) );
return new JsonResponse($testy);
}
public function createAction()
{
$em = $this->getDoctrine()->getManager();
$testy = new Testy();
$testy->setTitre('Magnifique');
$testy->setName('Helicoptere');
$em->persist($testy);
$em->flush();
return new Response('This is for create');
}
}
and what I get on my view page
[{},{}]
And it's true that there is 2 elements in my SQL table.
( I have create my entity with php bin/console doctrine:generate:entity without edition stuff in the "Testy" class or rep )
Entity/Testy
namespace KGN\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Testy
*
* #ORM\Table(name="testy")
* #ORM\Entity(repositoryClass="KGN\CoreBundle\Repository\TestyRepository")
*/
class Testy
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
*
* #return Testy
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set name
*
* #param string $name
*
* #return Testy
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
associed rep
namespace KGN\CoreBundle\Repository;
/**
* TestyRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TestyRepository extends \Doctrine\ORM\EntityRepository
{
}
Hi The Function findAll Return the correct answer but its return as array of Objects
And JsonResponse can't desplay Object.
to fixe that you have to create a custom function in your repository that return An array exemple
public function getAll() {
$qb = $this->createQueryBuilder('u');
return $qb->getQuery()->getArrayResult();
}
$em = $this->getDoctrine()->getManager();
$records = $em->getRepository("KGNCoreBundle:Testy")->findAll();
Hope its help you

Upload image using VichUploaderBundle

I have a problem with VichUploaderBundle, I followed all the instructions but I dont know how my Controller should handle this after finished form becouse image failed to uploaded and database did not write.
my Entity class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* #ORM\Entity
* #Vich\Uploadable
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
// ..... other fields
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName", size="imageSize")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageName;
/**
* #ORM\Column(type="integer")
*
* #var integer
*/
private $imageSize;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return Product
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
var_dump($image);
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*
* #return Product
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
/**
* #param integer $imageSize
*
* #return Product
*/
public function setImageSize($imageSize)
{
$this->imagesize = $imageSize;
return $this;
}
/**
* #return integer|null
*/
public function getImageSize()
{
return $this->imageSize;
}
}
my FormType class:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class AvatarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageFile', FileType::class, array('label' => 'Brochure (PDF file)'))
;
}
public function getName()
{
return 'avatar_form';
}
}
config:
vich_uploader:
db_driver: orm # or mongodb or propel or phpcr
mappings:
product_image:
uri_prefix: /image/avatar
upload_destination: '%kernel.root_dir%/../web/image/avatar'
Twig template:
<div>
{{ form_start(form) }}
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form.imageFile) }}
<button type="submit" class="btn btn-default">Submit</button>
{{ form_end(form) }}
</div>
and finally Controller:
namespace AppBundle\Controller\User;
use AppBundle\Entity\Product;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use AppBundle\Controller\InitController;
use AppBundle\Form\AvatarType;
class UserController extends Controller implements InitController
{
/**
* #Route("/user/avatar", name="AvatarAction")
*/
public function AvatarAction(Request $request)
{
$form = $this->createForm('AppBundle\Form\AvatarType',null,array(
// To set the action use $this->generateUrl('route_identifier')
'action' => $this->generateUrl('AvatarAction'),
'method' => 'POST'
));
$form->handleRequest($request);
if ($request->isMethod('POST')) {
if($form->isValid()){
//$track = new Product();
//$em = $this->getDoctrine()->getManager();
//$em->persist($track);
//$em->flush();
}
return $this->render('default/avatar.html.twig',array(
'form' => $form->createView()
));
}
}
Thanks for all your advice!
Maybe this is not the solution, but your line :
->add('imageFile', FileType::class, array('label' => 'Brochure (PDF file)')):
Should be :
->add('imageFile', VichFileType::class, array('label' => 'Brochure (PDF file)'))
More info : https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/form/vich_file_type.md
What Symfony tells you as error ?
Have a nice day

Sonata admin bundle, manipulate objects

I have 2 entities with one to many relationship project and prototype And I've been looking for a way to list the prototypes that belong to a project in the show action .
here is my project entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Projet
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ProjetRepository")
*/
class Projet
{
/**
* #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;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Prototype", mappedBy="projet",cascade={"persist"} , orphanRemoval=true)
* #ORM\OrderBy({"id"="ASC"})
*/
protected $prototypes;
public function __construct()
{
$this->prototypes = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime("now");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return Projet
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
public function __toString()
{
return $this->getNom();
}
/**
* 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 dateCreation
*
* #param \DateTime $dateCreation
* #return Projet
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
public function setPrototypes($prototypes)
{
if (count($prototypes) > 0) {
foreach ($prototypes as $i) {
$this->addPrototypes($i);
}
}
return $this;
}
/**
* Add prototypes
*
* #param \AppBundle\Entity\Prototype $prototypes
* #return Projet
*/
public function addPrototypes(\AppBundle\Entity\Prototype $prototypes)
{
$this->prototypes[]= $prototypes;
return $this;
}
public function addPrototype(\AppBundle\Entity\Prototype $prototype)
{
$prototype->setProjet($this);
$this->prototypes->add($prototype);
}
/**
* Remove prototypes
*
* #param \AppBunble\Entity\Prototype $prototypes
*/
public function removePrototypes(\AppBundle\Entity\Prototype $prototypes)
{
$this->prototypes->removeElement($prototypes);
}
/**
* Get prototypes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPrototypes()
{
return $this->prototypes;
}
}
and 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;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Projet", inversedBy="prototypes")
* #ORM\joinColumn(name="projet_id", referencedColumnName="id")
*/
private $projet;
/**
* 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;
}
}
In my projetAdmin I can show in the ShowAction the prototypes :
here is projetAdmin :
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Route\RouteCollection;
class ProjetAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('nom', 'text', array('label' => 'Nom'))
->add('description','text',array('label'=>'Description'))
->add('dateCreation', 'date', array('label' => 'Date de création'))
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('nom')
->add('dateCreation')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('nom')
->add('description')
->add('dateCreation')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
)
)
;
}
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('prototypes')
;
}
}
I get the prototypes ( names )
But I would like to "list" the prototypes that belong to the project like the list view ( name , description of the prototype...)
How can I do that ?
One way is to define the template for your prototypes field in showMapper
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper ->add('prototypes',null, array('template' => 'NamespaceYourBundle::Admin/prototypes.html.twig'));
}
Create Admin folder in your bundle's resources folder and create prototypes.html.twig file ,extend your twig template with sonata's base_show_field.html.twig template and in {% block field %} define your own markup looping through all related prototypes
{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
{% block field %}
{% spaceless %}
{% if object.getPrototypes() is not empty %}
<table class="table table-bordered table-striped">
<thead>
<tr class="sonata-ba-list-field-header">
<th class="sonata-ba-list-field-header-text">Nom</th>
<th class="sonata-ba-list-field-header-text">Description</th>
...
...
...
</tr>
</thead>
<tbody>
{% for prototype in object.getPrototypes() %}
<tr>
<td class="sonata-ba-list-field sonata-ba-list-field-text">{{ prototype.getNom() }}</td>
<td class="sonata-ba-list-field sonata-ba-list-field-text">{{ prototype.getDescription() }}</td>
...
...
...
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endspaceless %}
{% endblock %}
I found a way to resolve the problem but still I feel it's not the better way
I created a controller and overrided the showAction
<?php
namespace AppBundle\Controller;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class CRUDController extends Controller
{
public function showAction($id = null)
{
return $this->redirect($this->generateUrl('admin_app_prototype_list', array(
'filter[projet__id][value]'=>$id
)));
}
}
Then I get a list of prototypes that belong to a project.

FosUserBundle and doctrine request

When I execute this query
public function SearchByfournisseur($keyWord)
{
$qb = $this->createQueryBuilder('p')->distinct()->select('p');
$qb ->leftJoin('p.Fournisseur', 'f');
$qb ->where($qb->expr()->eq('f.username', $keyWord));
$query = $qb->getQuery();
$products = $query->getResult();
return $products;
}
I got this error:
[Semantical Error] line 0, col 110 near 'test': Error: 'test' is not defined.
But this one works perfectly:
public function SearchByfournisseur($keyWord)
{
$qb = $this->createQueryBuilder('p')->distinct()->select('p');
$qb ->leftJoin('p.Fournisseur', 'f');
$qb ->where($qb->expr()->eq('f.id', $keyWord));
$query = $qb->getQuery();
$products = $query->getResult();
return $products;
}
That means that I can't access to the user's attributes except his id.
Is there any away to solve this problem?
EDIT:
This is the concerned entities :
<?php
namespace Ecommerce\boutiqueBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FS\SolrBundle\Doctrine\Annotation as Solr;
/**
* Ecommerce\boutiqueBundle\Entity\Produit
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Ecommerce\boutiqueBundle\Entity\ProduitRepository")
*/
class Produit
{
/**
* #var integer $id
*#Solr\Id
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Ecommerce\UserBundle\Entity\User",inversedBy="Produits")
*
* #ORM\JoinColumn(name="Fournisseur_id", referencedColumnName="id")
*/
private $Fournisseur;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Fournisseur
*
* #param string $Fournisseur
*/
public function setFournisseur( $Fournisseur)
{
$this->Fournisseur = $Fournisseur;
}
/**
* Get Fournisseur
*
* #return string
*/
public function getFournisseur()
{
return $this->Fournisseur;
}
}
Fournisseur entity:
<?php
namespace Ecommerce\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="Ecommerce_user")
*/
class User extends BaseUser
{
public function __construct()
{
parent::__construct();
$this->Produits = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="Ecommerce\boutiqueBundle\Entity\Produit",
* mappedBy="Fournisseur")
*/
protected $Produits;
public function addProduit(\Ecommerce\boutiqueBundle\Entity\Produit $Produit)
{
$this->Produits[] = $Produit;
$Produit->setCategorie($this);
}
public function getProduits()
{
return $this->Produits;
}
}
You have to specify the join condition within the leftJoin() call.
public function SearchByfournisseur($keyWord)
{
$qb = $this->createQueryBuilder('p')->distinct()->select('p');
$qb ->leftJoin('p.Fournisseur', 'f', 'WITH', $qb->expr()->eq('f.username = ?', $keyWord));
$products = $query->getResult();
return $products;
}
I suggest you to read the Doctrine documentation chapter dealing about the QueryBuilder.

Resources