How do I perform twig result in symfony2? - symfony

here again, I have a problem. I am developing an application with an entity of about 3600 records, when I display the index.html.twig which is a list of products takes too long, about 20 sec to show the bootstrap table.
My entity:
<?php
namespace Nival\InventarioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* InProducto
*
* #ORM\Table(name="in_producto")
* #ORM\Entity
*/
class InProducto
{
/**
* #ORM\OneToMany(targetEntity="InProveedorProducto", mappedBy="InProducto", cascade={"persist"})
*/
protected $producto;
/**
* #ORM\OneToMany(targetEntity="InOrdenCompraDetalle", mappedBy="InProducto", cascade={"persist"})
*/
protected $productoOc;
public function __construct()
{
$this->producto = new ArrayCollection();
$this->productoOc = new ArrayCollection();
}
public function __toString() {
return $this->nombre;
}
/**
* #ORM\ManyToOne(targetEntity="InSubLinea", inversedBy="InProducto")
* #ORM\JoinColumn(name="id_sub_linea", referencedColumnName="id")
*/
protected $subLinea;
/**
* #ORM\ManyToOne(targetEntity="InUnidadMedida", inversedBy="InProducto")
* #ORM\JoinColumn(name="id_unidad_medida", referencedColumnName="id")
*/
protected $unidadMedida;
public function getDisplayName()
{
return sprintf('%s (%s)', $this->nombre, $this->unidadMedida);
}
/**
* #var integer
*
* #ORM\Column(name="id_producto", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idProducto;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=100, nullable=false)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="descripcion", type="string", length=100, nullable=true)
*/
private $descripcion;
/**
* #var integer
*
* #ORM\Column(name="id_unidad_medida", type="integer", nullable=false)
*/
private $idUnidadMedida;
/**
* #var string
*
* #ORM\Column(name="costo_promedio", type="decimal", precision=9, scale=6, nullable=false)
*/
private $costoPromedio;
/**
* #var integer
*
* #ORM\Column(name="id_sub_linea", type="integer", nullable=false)
*/
private $idSubLinea;
/**
* #var integer
*
* #ORM\Column(name="id_tipo_producto", type="integer", nullable=false)
*/
private $idTipoProducto;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_ingreso", type="date", nullable=false)
*/
private $fechaIngreso;
/**
* #var string
*
* #ORM\Column(name="precio1", type="decimal", precision=9, scale=2, nullable=false)
*/
private $precio1;
/**
* #var string
*
* #ORM\Column(name="precio2", type="decimal", precision=9, scale=2, nullable=false)
*/
private $precio2;
/**
* #var string
*
* #ORM\Column(name="precio3", type="decimal", precision=9, scale=2, nullable=false)
*/
private $precio3;
/**
* #var boolean
*
* #ORM\Column(name="inventariable", type="boolean", nullable=false)
*/
private $inventariable;
/**
* #var boolean
*
* #ORM\Column(name="facturable", type="boolean", nullable=false)
*/
private $facturable;
/**
* #var boolean
*
* #ORM\Column(name="activo", type="boolean", nullable=false)
*/
private $activo;
/**
* #var integer
*
* #ORM\Column(name="id_empresaa", type="integer", nullable=false)
*/
private $idEmpresaa;
/**
* Get idProducto
*
* #return integer
*/
public function getIdProducto()
{
return $this->idProducto;
}
/**
* Set nombre
*
* #param string $nombre
* #return InProducto
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set descripcion
*
* #param string $descripcion
* #return InProducto
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $descripcion;
return $this;
}
/**
* Get descripcion
*
* #return string
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* Set idUnidadMedida
*
* #param integer $idUnidadMedida
* #return InProducto
*/
public function setIdUnidadMedida($idUnidadMedida)
{
$this->idUnidadMedida = $idUnidadMedida;
return $this;
}
/**
* Get idUnidadMedida
*
* #return integer
*/
public function getIdUnidadMedida()
{
return $this->idUnidadMedida;
}
/**
* Set costoPromedio
*
* #param string $costoPromedio
* #return InProducto
*/
public function setCostoPromedio($costoPromedio)
{
$this->costoPromedio = $costoPromedio;
return $this;
}
/**
* Get costoPromedio
*
* #return string
*/
public function getCostoPromedio()
{
return $this->costoPromedio;
}
/**
* Set idSubLinea
*
* #param integer $idSubLinea
* #return InProducto
*/
public function setIdSubLinea($idSubLinea)
{
$this->idSubLinea = $idSubLinea;
return $this;
}
/**
* Get idSubLinea
*
* #return integer
*/
public function getIdSubLinea()
{
return $this->idSubLinea;
}
/**
* Set idTipoProducto
*
* #param integer $idTipoProducto
* #return InProducto
*/
public function setIdTipoProducto($idTipoProducto)
{
$this->idTipoProducto = $idTipoProducto;
return $this;
}
/**
* Get idTipoProducto
*
* #return integer
*/
public function getIdTipoProducto()
{
return $this->idTipoProducto;
}
/**
* Set fechaIngreso
*
* #param \DateTime $fechaIngreso
* #return InProducto
*/
public function setFechaIngreso($fechaIngreso)
{
$this->fechaIngreso = $fechaIngreso;
return $this;
}
/**
* Get fechaIngreso
*
* #return \DateTime
*/
public function getFechaIngreso()
{
return $this->fechaIngreso;
}
/**
* Set precio1
*
* #param string $precio1
* #return InProducto
*/
public function setPrecio1($precio1)
{
$this->precio1 = $precio1;
return $this;
}
/**
* Get precio1
*
* #return string
*/
public function getPrecio1()
{
return $this->precio1;
}
/**
* Set precio2
*
* #param string $precio2
* #return InProducto
*/
public function setPrecio2($precio2)
{
$this->precio2 = $precio2;
return $this;
}
/**
* Get precio2
*
* #return string
*/
public function getPrecio2()
{
return $this->precio2;
}
/**
* Set precio3
*
* #param string $precio3
* #return InProducto
*/
public function setPrecio3($precio3)
{
$this->precio3 = $precio3;
return $this;
}
/**
* Get precio3
*
* #return string
*/
public function getPrecio3()
{
return $this->precio3;
}
/**
* Set inventariable
*
* #param boolean $inventariable
* #return InProducto
*/
public function setInventariable($inventariable)
{
$this->inventariable = $inventariable;
return $this;
}
/**
* Get inventariable
*
* #return boolean
*/
public function getInventariable()
{
return $this->inventariable;
}
/**
* Set facturable
*
* #param boolean $facturable
* #return InProducto
*/
public function setFacturable($facturable)
{
$this->facturable = $facturable;
return $this;
}
/**
* Get facturable
*
* #return boolean
*/
public function getFacturable()
{
return $this->facturable;
}
/**
* Set activo
*
* #param boolean $activo
* #return InProducto
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activo
*
* #return boolean
*/
public function getActivo()
{
return $this->activo;
}
public function setUnidadMedida($unidadMedida)
{
$this->unidadMedida = $unidadMedida;
return $this;
}
/**
* Get unidadMedida
*
* #return integer
*/
public function getUnidadMedida()
{
return $this->unidadMedida;
}
public function setSubLinea($subLinea)
{
$this->subLinea = $subLinea;
return $this;
}
/**
* Get subLinea
*
* #return integer
*/
public function getSubLinea()
{
return $this->subLinea;
}
public function setProducto($producto)
{
$this->producto = $producto;
return $this;
}
/**
* Get producto
*
* #return integer
*/
public function getProducto()
{
return $this->producto;
}
public function setProductoOc($productoOc)
{
$this->productoOc = $productoOc;
return $this;
}
/**
* Get productoOc
*
* #return integer
*/
public function getProductoOc()
{
return $this->productoOc;
}
/**
* Set idEmpresaa
*
* #param integer $idEmpresaa
* #return InProducto
*/
public function setIdEmpresaa($idEmpresaa)
{
$this->idEmpresaa = $idEmpresaa;
return $this;
}
/**
* Get idEmpresaa
*
* #return integer
*/
public function getIdEmpresaa()
{
return $this->idEmpresaa;
}
}
My controller:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('session');
$id_empresaa = $session->get('idempresa');
$entities = $em->getRepository('NivalInventarioBundle:InProducto')->findBy(array(
'idEmpresaa' => $id_empresaa
));
return $this->render('NivalInventarioBundle:InProducto:index.html.twig', array(
'entities' => $entities,
));
}
My twig:
{% extends 'NivalInventarioBundle:Default:index.html.twig' %}
{% block content %}
{% block inventario_menu %}
{{ parent() }}
{% endblock %}
<h3>Productos</h3>
<div class="row" style = margin-bottom:55px;">
<div class="col-md-12">
<table id="ftable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Código</th>
<th>Nombre</th>
<th>Unidad</th>
<th>Costo</th>
<th>Sub-Linea</th>
<th>Linea</th>
<th>Invent.</th>
<th>Factura</th>
<th>Activo</th>
<th>Opción</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.idProducto }}</td>
<td>{{ entity.nombre }}</td>
<td>{{ entity.unidadMedida.nombre }}</td>
<td class="text-right">{{ entity.costoPromedio|number_format(4) }}</td>
<td>{{ entity.subLinea.nombre }}</td>
<td>{{ entity.subLinea.linea.nombre }}</td>
<td>
{% if entity.inventariable == 0 %}
No
{% elseif entity.inventariable == 1 %}
Sí
{% endif %}
</td>
<td>
{% if entity.facturable == 0 %}
No
{% elseif entity.facturable == 1 %}
Sí
{% endif %}
</td>
<td>
{% if entity.activo == 0 %}
No
{% elseif entity.activo == 1 %}
Sí
{% endif %}
</td>
<td class = "actions">
<a href="{{ path('inproducto_show', { 'id': entity.idProducto }) }}"
class = "btn btn-sm btn-info glyphicon glyphicon-search" data-toggle="tooltip" title="Ver"></a>
{% if app.user.nivel > 60 %}
<a href="{{ path('inproducto_edit', { 'id': entity.idProducto }) }}"
class = "btn btn-sm btn-primary glyphicon glyphicon-edit" data-toggle="tooltip" title="Editar"></a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if app.user.nivel > 30 %}
<div class="col-md-12">
<a href="{{ path('inproducto_new') }}"
class = "btn btn-success glyphicon glyphicon-plus" data-toggle="tooltip" title="Nuevo"></a>
</div>
{% endif %}
</div>
{% endblock %}
I have been searching on internet, but cant find a solution.
I installed APC in my VPS, and setup the config_prod.yml
doctrine:
orm:
auto_mapping: true
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
console:
type: console
Please give me a clue!

Set eager fetch mode for associations subLinea and unidadMedida.
With this fetch mode all data from DB will be retrieved in one request.
/**
* #ORM\ManyToOne(targetEntity="InSubLinea", inversedBy="InProducto", fetch="EAGER")
* #ORM\JoinColumn(name="id_sub_linea", referencedColumnName="id")
*/
protected $subLinea;
/**
* #ORM\ManyToOne(targetEntity="InUnidadMedida", inversedBy="InProducto", fetch="EAGER")
* #ORM\JoinColumn(name="id_unidad_medida", referencedColumnName="id")
*/
protected $unidadMedida;
Install twig C extension
http://twig.sensiolabs.org/doc/installation.html#installing-the-c-extension

I used KNPPaginatorBundle to paginate results and It works outstanding, I recomended it: https://github.com/KnpLabs/KnpPaginatorBundle. Checked in this post: How to display large table in twig with symfony?

Related

Symfony2.7 displaying combox items in twig

I have a table named company and departments. Company having one to many relationship with departments. I have created both the entities and specified the relationships in both. Please take a look at both the entities
Department.php
<?php
namespace Benerite\CompanyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Department
*
* #ORM\Table("departments")
* #ORM\Entity(repositoryClass="Benerite\CompanyBundle\Entity\DepartmentRepository")
*/
class Department
{
/**
* #ORM\ManyToOne(targetEntity="Company", inversedBy="departments")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
protected $company;
/**
* #var employeeJobInfo
*
* #ORM\OneToMany(targetEntity="Benerite\EmployeeBundle\Entity\EmployeeJobInfo", mappedBy="department")
*/
protected $employeeJobInfo;
public function __construct()
{
$this->employeeJobInfo = new ArrayCollection();
}
function getCompany() {
return $this->company;
}
function getEmployeeJobInfo() {
return $this->employeeJobInfo;
}
function setCompany(Company $company) {
$this->company = $company;
}
function setEmployeeJobInfo(\Benerite\EmployeeBundle\Entity\EmployeeJobInfo $employeeJobInfo) {
$this->employeeJobInfo = $employeeJobInfo;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="company_id", type="integer" , nullable = false)
*/
private $companyId;
/**
* #var string
*
* #ORM\Column(name="department_name", type="string", length=255)
*/
private $departmentName;
/**
* #var string
*
* #ORM\Column(name="department_status", type="string", length=255)
*/
private $departmentStatus;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set companyId
*
* #param integer $companyId
*
* #return Department
*/
public function setCompanyId($companyId)
{
$this->companyId = $companyId;
return $this;
}
/**
* Get companyId
*
* #return integer
*/
public function getCompanyId()
{
return $this->companyId;
}
/**
* Set departmentName
*
* #param string $departmentName
*
* #return Department
*/
public function setDepartmentName($departmentName)
{
$this->departmentName = $departmentName;
return $this;
}
/**
* Get departmentName
*
* #return string
*/
public function getDepartmentName()
{
return $this->departmentName;
}
/**
* Set departmentStatus
*
* #param string $departmentStatus
*
* #return Department
*/
public function setDepartmentStatus($departmentStatus)
{
$this->departmentStatus = $departmentStatus;
return $this;
}
/**
* Get departmentStatus
*
* #return string
*/
public function getDepartmentStatus()
{
return $this->departmentStatus;
}
}
Company.php
<?php
namespace Benerite\CompanyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Company
*
* #ORM\Table("companies")
* #ORM\Entity(repositoryClass="Benerite\CompanyBundle\Entity\CompanyRepository")
*/
class Company
{
/**
* #var departments
* #ORM\OneToMany(targetEntity="Department", mappedBy="company")
*/
protected $departments;
/**
* #var divisions
* #ORM\OneToMany(targetEntity="Division", mappedBy="company")
*/
protected $divisions;
/**
* #var employmentStatuses
* #ORM\OneToMany(targetEntity="EmploymentStatus", mappedBy="company")
*/
protected $employmentStatuses;
/**
* #var jobTitles
* #ORM\OneToMany(targetEntity="JobTitle", mappedBy="company")
*/
protected $jobTitles;
/**
* #var companyLocations
* #ORM\OneToMany(targetEntity="Location", mappedBy="company")
*/
protected $companyLocations;
/**
* #var remunerationChangeReasons
* #ORM\OneToMany(targetEntity="RemunerationChangeReason", mappedBy="company")
*/
protected $remunerationChangeReasons;
/**
* #var roles
* #ORM\OneToMany(targetEntity="Role", mappedBy="company")
*/
protected $roles;
/**
* #var subscriptionDetails
*
* #ORM\OneToMany(targetEntity="SubscriptionDetail", mappedBy="company")
*/
protected $subscriptionDetails;
public function __construct() {
$this->departments = new ArrayCollection();
$this->divisions = new ArrayCollection();
$this->employmentStatuses = new ArrayCollection();
$this->jobTitles = new ArrayCollection();
$this->companyLocations = new ArrayCollection();
$this->remunerationChangeReasons = new ArrayCollection();
$this->roles = new ArrayCollection();
$this->subscriptionDetails = new ArrayCollection();
}
function getDepartments() {
return $this->departments;
}
function getDivisions() {
return $this->divisions;
}
function getEmploymentStatuses() {
return $this->employmentStatuses;
}
function getJobTitles() {
return $this->jobTitles;
}
function getCompanyLocations() {
return $this->companyLocations;
}
function getRemunerationChangeReasons() {
return $this->remunerationChangeReasons;
}
function getRoles() {
return $this->roles;
}
function getSubscriptionDetails() {
return $this->subscriptionDetails;
}
function setDepartments(Department $departments) {
$this->departments = $departments;
}
function setDivisions(Division $divisions) {
$this->divisions = $divisions;
}
function setEmploymentStatuses(\Benerite\EmployeeBundle\Entity\EmployeeEmploymentStatus $employmentStatuses) {
$this->employmentStatuses = $employmentStatuses;
}
function setJobTitles(JobTitle $jobTitles) {
$this->jobTitles = $jobTitles;
}
function setCompanyLocations(Location $companyLocations) {
$this->companyLocations = $companyLocations;
}
function setRemunerationChangeReasons(RemunerationChangeReason $remunerationChangeReasons) {
$this->remunerationChangeReasons = $remunerationChangeReasons;
}
function setRoles(Role $roles) {
$this->roles = $roles;
}
function setSubscriptionDetails(SubscriptionDetail $subscriptionDetails) {
$this->subscriptionDetails = $subscriptionDetails;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="company_name", type="string", length=255)
*/
private $companyName;
/**
* #var string
*
* #ORM\Column(name="company_reg_code", type="string", length=255)
*/
private $companyRegCode;
/**
* #var string
*
* #ORM\Column(name="account_owner", type="string", length=255)
*/
private $accountOwner;
/**
* #var string
*
* #ORM\Column(name="account_email", type="string", length=255)
*/
private $accountEmail;
/**
* #var string
*
* #ORM\Column(name="company_url", type="string", length=255)
*/
private $companyUrl;
/**
* #var string
*
* #ORM\Column(name="company_status", type="string", length=255)
*/
private $companyStatus;
/**
* #var \DateTime
*
* #ORM\Column(name="created_date", type="datetime")
*/
private $createdDate;
/**
* #var \DateTime
*
* #ORM\Column(name="last_updated_date", type="datetime")
*/
private $lastUpdatedDate;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set companyName
*
* #param string $companyName
*
* #return Company
*/
public function setCompanyName($companyName)
{
$this->companyName = $companyName;
return $this;
}
/**
* Get companyName
*
* #return string
*/
public function getCompanyName()
{
return $this->companyName;
}
/**
* Set companyRegCode
*
* #param string $companyRegCode
*
* #return Company
*/
public function setCompanyRegCode($companyRegCode)
{
$this->companyRegCode = $companyRegCode;
return $this;
}
/**
* Get companyRegCode
*
* #return string
*/
public function getCompanyRegCode()
{
return $this->companyRegCode;
}
/**
* Set accountOwner
*
* #param string $accountOwner
*
* #return Company
*/
public function setAccountOwner($accountOwner)
{
$this->accountOwner = $accountOwner;
return $this;
}
/**
* Get accountOwner
*
* #return string
*/
public function getAccountOwner()
{
return $this->accountOwner;
}
/**
* Set accountEmail
*
* #param string $accountEmail
*
* #return Company
*/
public function setAccountEmail($accountEmail)
{
$this->accountEmail = $accountEmail;
return $this;
}
/**
* Get accountEmail
*
* #return string
*/
public function getAccountEmail()
{
return $this->accountEmail;
}
/**
* Set companyUrl
*
* #param string $companyUrl
*
* #return Company
*/
public function setCompanyUrl($companyUrl)
{
$this->companyUrl = $companyUrl;
return $this;
}
/**
* Get companyUrl
*
* #return string
*/
public function getCompanyUrl()
{
return $this->companyUrl;
}
/**
* Set companyStatus
*
* #param string $companyStatus
*
* #return Company
*/
public function setCompanyStatus($companyStatus)
{
$this->companyStatus = $companyStatus;
return $this;
}
/**
* Get companyStatus
*
* #return string
*/
public function getCompanyStatus()
{
return $this->companyStatus;
}
/**
* Set createdDate
*
* #param \DateTime $createdDate
*
* #return Company
*/
public function setCreatedDate($createdDate)
{
$this->createdDate = $createdDate;
return $this;
}
/**
* Get createdDate
*
* #return \DateTime
*/
public function getCreatedDate()
{
return $this->createdDate;
}
/**
* Set lastUpdatedDate
*
* #param \DateTime $lastUpdatedDate
*
* #return Company
*/
public function setLastUpdatedDate($lastUpdatedDate)
{
$this->lastUpdatedDate = $lastUpdatedDate;
return $this;
}
/**
* Get lastUpdatedDate
*
* #return \DateTime
*/
public function getLastUpdatedDate()
{
return $this->lastUpdatedDate;
}
public function __toString()
{
return (string)$this->getId();
}
}
I have created schemas using both this and its correct. I have generated crud forms for both entities and its also giving me the correct forms. The issue is that, in my departments create and edit page, its giving me a combobox like this when rendering
<select id="benerite_companybundle_department_company" name="benerite_companybundle_department[company]">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
This is not really what I want it should mbe like
<select id="benerite_companybundle_department_company" name="benerite_companybundle_department[company]">
<option value="">please select</option>
<option value="1">comapny 1</option>
<option value="2">comapny 2</option>
</select>
Here is my new.twig.html file
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Department creation</h1>
{{ form_start(form) }}
<div>
{{ form_label(form.company) }}
{{ form_widget(form.company) }}
</div>
<div>
{{ form_label(form.departmentStatus) }}
{{ form_widget(form.departmentStatus) }}
</div>
<div>
{{ form_label(form.departmentName) }}
{{ form_widget(form.departmentName) }}
</div>
{{ form_end(form) }}
<ul class="record_actions">
<li>
<a href="{{ path('department') }}">
Back to the list
</a>
</li>
</ul>
{% endblock %}
I am using symfony2.7 and mysql as database.
You can do like below:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('company', 'entity', array(
'class' => 'BeneriteCompanyBundle:Company',
'choice_label' => 'companyName'
)
->add('departmentName')
->add('departmentStatus')
;
}
I hope this will work as you want.
Or if you want to write custom query go through below url:
http://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities

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.

How to make retrieve data from another controller Symfony2

I'm new with Symfony2 and I have a question that I could not fully solve by myself. I'm programming an application and use the tables client and project. Every project has one client and every client can have multiple projects.
The autonomous display of clients- and projectstables does already work, but I also have to display the projects in the frontend of clients. I already tried multiple ways to do so but I did not have any success so far.
Could you tell me what I have to put in my ClientController-, config.yml and routing.yml-File in order to display the projecttables in the show.html.twig file of client?
I thank you in advance for your answer
Url: http://dev.pingag.ch/Symfony/web/app_dev.php/clients/
ClientController.php
namespace Acme\KeywordBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\KeywordBundle\Entity\Client;
use Acme\KeywordBundle\Entity\Project;
use Acme\KeywordBundle\Form\ClientType;
/**
* Client controller.
*
* #Route("/clients")
*/
class ClientController extends Controller
{
/**
* Lists all Client entities.
*
* #Route("/", name="clients")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AcmeKeywordBundle:Client')->findAll();
return array(
'entities' => $entities,
);
}
...
...
...
}
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
...
...
...
routing.yml
acme_keyword:
resource: "#AcmeKeywordBundle/Controller"
type: annotation
client.php
<?php
namespace Acme\KeywordBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Client
*
* #ORM\Table()
* #ORM\Entity
*/
class client
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=true)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
// Anfang Kopiert von Anleitung
/**
* #ORM\OneToMany(targetEntity="Project", mappedBy="client")
*/
protected $projects;
/**
* #ORM\OneToMany(targetEntity="File", mappedBy="client")
*/
protected $files;
/**
* #ORM\OneToMany(targetEntity="Contact", mappedBy="client")
*/
protected $contacts;
public function __construct()
{
$this->projects = new ArrayCollection();
$this->files = new ArrayCollection();
$this->contacts = new ArrayCollection();
}
// Ende Kopiert von Anleitung
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
* #Assert\NotBlank()
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime", nullable=true)
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updatedAt", type="datetime", nullable=true)
*/
private $updatedAt;
/**
* #var string
*
* #ORM\Column(name="logoFileName", type="string", length=255, nullable=true)
*/
private $logoFileName;
/**
* #var string
*
* #ORM\Column(name="logoContentType", type="string", length=255, nullable=true)
*/
private $logoContentType;
/**
* #var integer
*
* #ORM\Column(name="logoFileSize", type="integer", nullable=true)
*/
private $logoFileSize;
/**
* #var \DateTime
*
* #ORM\Column(name="logoUpdatedAt", type="datetime", nullable=true)
*/
private $logoUpdatedAt;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Client
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set createtAt
*
* #param \DateTime $createtAt
* #return Client
*/
public function setCreatetAt($createtAt)
{
$this->createtAt = $createtAt;
return $this;
}
/**
* Get createtAt
*
* #return \DateTime
*/
public function getCreatetAt()
{
return $this->createtAt;
}
/**
* Set updatetAt
*
* #param \DateTime $updatetAt
* #return Client
*/
public function setUpdatetAt($updatetAt)
{
$this->updatetAt = $updatetAt;
return $this;
}
/**
* Get updatetAt
*
* #return \DateTime
*/
public function getUpdatetAt()
{
return $this->updatetAt;
}
/**
* Set logoFileName
*
* #param string $logoFileName
* #return Client
*/
public function setLogoFileName($logoFileName)
{
$this->logoFileName = $logoFileName;
return $this;
}
/**
* Get logoFileName
*
* #return string
*/
public function getLogoFileName()
{
return $this->logoFileName;
}
/**
* Set logoContentType
*
* #param string $logoContentType
* #return Client
*/
public function setLogoContentType($logoContentType)
{
$this->logoContentType = $logoContentType;
return $this;
}
/**
* Get logoContentType
*
* #return string
*/
public function getLogoContentType()
{
return $this->logoContentType;
}
/**
* Set logoFileSize
*
* #param integer $logoFileSize
* #return Client
*/
public function setLogoFileSize($logoFileSize)
{
$this->logoFileSize = $logoFileSize;
return $this;
}
/**
* Get logoFileSize
*
* #return integer
*/
public function getLogoFileSize()
{
return $this->logoFileSize;
}
/**
* Set logoUpdatedAt
*
* #param \DateTime $logoUpdatedAt
* #return Client
*/
public function setLogoUpdatedAt($logoUpdatedAt)
{
$this->logoUpdatedAt = $logoUpdatedAt;
return $this;
}
/**
* Get logoUpdatedAt
*
* #return \DateTime
*/
public function getLogoUpdatedAt()
{
return $this->logoUpdatedAt;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Client
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Client
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Add projects
*
* #param \Acme\KeywordBundle\Entity\Project $projects
* #return Client
*/
public function addProject(\Acme\KeywordBundle\Entity\Project $projects)
{
$this->projects[] = $projects;
return $this;
}
/**
* Remove projects
*
* #param \Acme\KeywordBundle\Entity\Project $projects
*/
public function removeProject(\Acme\KeywordBundle\Entity\Project $projects)
{
$this->projects->removeElement($projects);
}
/**
* Get projects
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProjects()
{
return $this->projects;
}
/**
* Add files
*
* #param \Acme\KeywordBundle\Entity\File $files
* #return Client
*/
public function addFile(\Acme\KeywordBundle\Entity\File $files)
{
$this->files[] = $files;
return $this;
}
/**
* Remove files
*
* #param \Acme\KeywordBundle\Entity\File $files
*/
public function removeFile(\Acme\KeywordBundle\Entity\File $files)
{
$this->files->removeElement($files);
}
/**
* Get files
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFiles()
{
return $this->files;
}
/**
* Add contacts
*
* #param \Acme\KeywordBundle\Entity\Contact $contacts
* #return Client
*/
public function addContact(\Acme\KeywordBundle\Entity\Contact $contacts)
{
$this->contacts[] = $contacts;
return $this;
}
/**
* Remove contacts
*
* #param \Acme\KeywordBundle\Entity\Contact $contacts
*/
public function removeContact(\Acme\KeywordBundle\Entity\Contact $contacts)
{
$this->contacts->removeElement($contacts);
}
/**
* Get contacts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContacts()
{
return $this->contacts;
}
public function __toString()
{
return $this->name;
}
}
show.html.twig of the cliententity
the project list should schow up under Project list
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Client</h1>
<table class="record_properties">
<tbody>
<!--
<tr>
<th>Id</th>
<td>{{ entity.id }}</td>
</tr>
<tr>
-->
<th>Name</th>
<td>{{ entity.name }}</td>
</tr>
<tr>
<!--
<th>Createdat</th>
<td>{{ entity.createdAt|date('Y-m-d H:i:s') }}</td>
</tr>
<tr>
<th>Updatedat</th>
<td>{{ entity.updatedAt|date('Y-m-d H:i:s') }}</td>
</tr>
<tr>
<th>Logofilename</th>
<td>{{ entity.logoFileName }}</td>
</tr>
<tr>
<th>Logocontenttype</th>
<td>{{ entity.logoContentType }}</td>
</tr>
<tr>
<th>Logofilesize</th>
<td>{{ entity.logoFileSize }}</td>
</tr>
<tr>
<th>Logoupdatedat</th>
<td>{{ entity.logoUpdatedAt|date('Y-m-d H:i:s') }}</td>
</tr>
-->
</tbody>
</table>
<ul class="record_actions">
<li>
<a href="{{ path('clients') }}">
Back to the list
</a>
</li>
<li>
<a href="{{ path('clients_edit', { 'id': entity.id }) }}">
Edit
</a>
</li>
<li>{{ form(delete_form) }}</li>
</ul>
<h1>Project list</h1>
{% endblock %}
If your entity relations are configured correctly (what they seem to be), then you can acces the projects array direclty in twig:
{% for project in entity.projects %}
Name: {{ project.name }}
...
{% endfor %}

Mapping doesn't work ORM

I have this example:
Log.php
<?php
// src/Mailing/MailingBundle/Entity/Log.php
namespace Mailing\MailingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="log")
*/
class Log
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=20)
*/
protected $action;
public function getAction() {
return $this->action;
}
public function setAction($action) {
$this->action = $action;
}
/**
* #ORM\Column(type="datetime")
*/
protected $date;
public function getDate() {
return $this->date;
}
public function setDate($date) {
$this->date = $date;
}
/**
* #ORM\Column(type="integer", name="mail_id")
* #ORM\oneToOne(targetEntity="Mail")
*/
protected $mail;
public function getMail() {
return $this->mail;
}
public function setMail($mail) {
$this->mail = $mail;
}
/**
* #ORM\Column(type="integer", name="template_id")
* #ORM\oneToOne(targetEntity="Template")
*/
protected $template;
public function getTemplate() {
return $this->template;
}
public function setTemplate($template) {
$this->template = $template;
}
}
Mail.php
<?php
// src/Mailing/MailingBundle/Entity/Mail.php
namespace Mailing\MailingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="mail")
*/
class Mail
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function getId() {
return $this->id;
}
/**
* #ORM\Column(type="string", length=200)
*/
protected $address;
/**
*
* #return type
*/
public function getAddress() {
return $this->address;
}
/**
*
* #param \Mailing\MailingBundle\Entity\Mail $surname
*/
public function setAddress($address)
{
$this->address = $address;
}
/**
* #ORM\Column(type="string", length=200)
*/
protected $name;
/**
*
* #return type
*/
public function getName() {
return $this->name;
}
/**
*
* #param \Mailing\MailingBundle\Entity\Mail $surname
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #ORM\Column(type="string", length=200)
*/
protected $surname;
/**
*
* #return type
*/
public function getSurname() {
return $this->surname;
}
/**
*
* #param \Mailing\MailingBundle\Entity\Mail $surname
*/
public function setSurname($surname)
{
$this->surname = $surname;
}
/**
* #ORM\Column(type="boolean")
*/
protected $subscribed;
/**
*
* #return type
*/
public function getSubscribed() {
return $this->subscribed;
}
/**
*
* #param \Mailing\MailingBundle\Entity\Mail $subscribed
*/
public function setSubscribed($subscribed)
{
$this->subscribed = $subscribed;
}
/**
* #ORM\manyToMany(targetEntity="Inventory", inversedBy="articles")
* #ORM\joinTable(
* name="mail_inventory",
* joinColumns={
* #ORM\joinColumn(name="mail_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\joinColumn(name="iventory_id", referencedColumnName="id")
* }
* )
*/
protected $inventories;
/**
* #return DoctrineCommonCollectionsCollection;
*/
public function getInventories()
{
return $this->inventories;
}
/**
* #ORM\Column(type="string", length=128)
*/
protected $hash;
public function getHash() {
return $this->hash;
}
public function setHash($hash) {
$this->hash = $hash;
}
}
LogController.php
<?php
// src/Mailing/MailingBundle/Controller/LogController.php
namespace Mailing\MailingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LogController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$records = $em->getRepository('MailingBundle:Log')->findAll();
return $this->render('MailingBundle:Log:index.html.twig', array('logs' =>$records));
}
}
Template:
{# src/Mailing/MailingBundle/Resources/views/Log/index.html.twig #}
{% extends 'MailingBundle::layout.html.twig' %}
{% block title %}
Log
{% endblock %}
{% block headline %}
Log
{% endblock %}
{% block content %}
{% if logs %}
<table>
<tr><th>Date</th><th>E-mail</th><th>Template</th></tr>
{% for log in logs %}
<tr><td>{{ log.date|date('H:i j.n.Y') }}</td><td>{{ log.action }}</td><td>{{ log.mail.address }}</td><td>{{ log.template.name }}</td></tr>
{% endfor %}
</table>
{% else %}
No records to show...
{% endif %}
{% endblock %}
It generates this error:
Impossible to access an attribute ("address") on a integer variable ("1") in MailingBundle:Log:index.html.twig at line 17
This is DB Schema
log
id int(11) NO PRI NULL auto_increment
action varchar(20) YES NULL
date datetime YES NULL
mail_id int(11) NO MUL NULL
template_id int(11) YES MUL NULL
mail
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
address varchar(200) NO NULL
name varchar(200) YES NULL
surname varchar(200) YES NULL
subscribed tinyint(1) YES 1
hash varchar(128) NO NULL
Thank you for help.
According to the documentation: doctrine doc
You were wrong to declare the record:
/**
* #ORM\Column(type="integer", name="mail_id")
* #ORM\oneToOne(targetEntity="Mail")
*/
protected $mail;
instead must be:
/**
* #OneToOne(targetEntity="Mail")
* #JoinColumn(name="mail_id", referencedColumnName="id")
*/
protected $mail;
The same thing for $template.
EDIT:
If you can not make it work you can try the bidirectional association: onetoone bidirectional
Log.php
/**
* #OneToOne(targetEntity="Mail", inversedBy="log")
* #JoinColumn(name="mail_id", referencedColumnName="id")
*/
protected $mail;
Mail.php
/**
* #OneToOne(targetEntity="Log", mappedBy="mail")
**/
private $log;

Query result found but not displayed in Symfony

Well, I don't really see this one.
This is a simple page where I try to display results of a joined query.
Here is the controller code :
public function pageApproachUpdateAction($pageId)
{
$em=$this->getDoctrine()->getEntityManager();
$pageWithMapItems = $em->getRepository('bndmyBundle:Page')->getPageWithMapItems($pageId);
return $this->render('bndmyBundle:test.html.twig', array(
'pageWithMapItems' => $pageWithMapItems
));
Here is the query :
public function getPageWithMapItems($pageId) {
$qb = $this->createQueryBuilder('p')
->leftJoin('p.mapItems', 'm')
->where('p.id = :pageId')
->setParameter('pageId', $pageId)
->addSelect('m');
return $qb->getQuery()
->getSingleResult();
}
Here is the twig code :
<body>
{% for mapitem in pageWithMapItems %}
item {{mapitem.id}}<br/>
{% else %}
No result
{% endfor %}
</body>
Here is the Page entity :
<?php
namespace bnd\myBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* bnd\myBundle\Entity\Page
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="bnd\myBundle\Entity\PageRepository")
*/
class Page
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="bnd\myBundle\Entity\Route", mappedBy="page")
*/
private $routes;
/**
* #ORM\OneToMany(targetEntity="bnd\myBundle\Entity\MapItem", mappedBy="page")
*/
private $mapItems;
/**
* #var smallint $number
*
* #ORM\Column(name="number", type="smallint")
*/
private $number;
/**
* #var string $background
*
* #ORM\Column(name="background", type="string", length=255, nullable="true")
*/
private $background;
/**
* #var string $type
*
* #ORM\Column(name="type", type="string", length=30)
*/
private $type;
/**
* #var string $description
*
* #ORM\Column(name="description", type="text", nullable="true")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set background
*
* #param string $background
*/
public function setBackground($background)
{
$this->background = $background;
}
/**
* Get background
*
* #return string
*/
public function getBackground()
{
return $this->background;
}
/**
* Set type
*
* #param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function __construct()
{
$this->routes = new \Doctrine\Common\Collections\ArrayCollection();
$this->mapItems = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add routes
*
* #param bnd\myBundle\Entity\Route $routes
*/
public function addRoute(\bnd\myBundle\Entity\Route $routes)
{
$this->routes[] = $routes;
}
/**
* Get routes
*
* #return Doctrine\Common\Collections\Collection
*/
public function getRoutes()
{
return $this->routes;
}
/**
* Set number
*
* #param smallint $number
*/
public function setNumber($number)
{
$this->number = $number;
}
/**
* Get number
*
* #return smallint
*/
public function getNumber()
{
return $this->number;
}
/**
* Add mapItems
*
* #param bnd\myBundle\Entity\MapItem $mapItems
*/
public function addMapItem(\bnd\myBundle\Entity\MapItem $mapItems)
{
$this->mapItems[] = $mapItems;
}
/**
* Get mapItems
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMapItems()
{
return $this->mapItems;
}
/**
* Set description
*
* #param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return text
*/
public function getDescription()
{
return $this->description;
}
}
And the MapItem entity :
namespace bnd\myBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* bnd\myBundle\Entity\MapItem
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="bnd\myBundle\Entity\MapItemRepository")
*/
class MapItem
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="bnd\myBundle\Entity\Page", inversedBy="mapItems")
* #ORM\JoinColumn(nullable=false)
*/
private $page;
/**
* #var string $type
*
* #ORM\Column(name="type", type="string", length=255)
*/
private $type;
/**
* #var string $latlng
*
* #ORM\Column(name="latlng", type="text")
*/
private $latlng;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set latlng
*
* #param string $latlng
*/
public function setLatlng($latlng)
{
$this->latlng = $latlng;
}
/**
* Get latlng
*
* #return string
*/
public function getLatlng()
{
return $this->latlng;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set page
*
* #param bnd\myBundle\Entity\Page $page
*/
public function setPage(\bnd\myBundle\Entity\Page $page)
{
$this->page = $page;
}
/**
* Get page
*
* #return bnd\myBundle\Entity\Page
*/
public function getPage()
{
return $this->page;
}
}
No result is displayed, but there should be one!
I don't have any exception, no typo mistakes I guess
I checked the profiler to read the actual queries performed ; I tested them with PhpMyAdmin, and none of them have no result.
It's a very simple and basic case. So, what did I did wrong ?
Thanks :)
So the thing is you've a one-to-many on your mapItems, so doctrine will return you an arrayCollection.
Your mapItems wasn't displayed in twig because you have to make your for loop on pageWithMapItems.mapItems, if you do it directly on pageWithMapItems it'll not work because your pageWithMapItems variable contain un object of page and not an array.
So this should work:
<body>
{% for mapitem in pageWithMapItems.mapItems %}
item {{mapitem.id}}<br/>
{% else %}
No result
{% endfor %}
</body>
Hope i'm clear !

Resources