Mapping doesn't work ORM - symfony

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;

Related

the image doesn't appeare on the web page

i use vich uploader bundle to display images added to my data base
here is my code
config.yml :
vich_uploader:
db_driver: orm
mappings:
cours_image:
uri_prefix: /images/cours
upload_destination: '%kernel.root_dir%/../web/images/cours'
inject_on_load: true
delete_on_update: false
delete_on_remove: true
namer: vich_uploader.namer_origname
the entity
<?php
namespace DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
/**
* CoursCode
*
* #ORM\Table(name="cours_code")
* #ORM\Entity
* #Vich\Uploadable
*/
class CoursCode
{
/**
* #var integer
*
* #ORM\Column(name="id_cours", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idCours;
/**
* #var string
*
* #ORM\Column(name="titre_cours", type="string", length=50, nullable=false)
*/
private $titreCours;
/**
* #var string
*
* #ORM\Column(name="contenu_cours", type="text", length=65535, nullable=false)
*/
private $contenuCours;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="cours_image", fileNameProperty="imageName", size="imageSize")
* #Assert\File(maxSize="1200k",mimeTypes={"image/png", "image/jpeg", "image/pjpeg"})
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageName;
/**
* #ORM\Column(type="integer", nullable=true)
*
* #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 CoursCode
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($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 CoursCode
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
/**
* #param integer $imageSize
*
* #return CoursCode
*/
public function setImageSize($imageSize)
{
$this->imagesize = $imageSize;
return $this;
}
/**
* #return integer|null
*/
public function getImageSize()
{
return $this->imageSize;
}
/**
* #return int
*/
public function getIdCours()
{
return $this->idCours;
}
/**
* #param int $idCours
*/
public function setIdCours($idCours)
{
$this->idCours = $idCours;
}
/**
* #return string
*/
public function getTitreCours()
{
return $this->titreCours;
}
/**
* #param string $titreCours
*/
public function setTitreCours($titreCours)
{
$this->titreCours = $titreCours;
}
/**
* #return string
*/
public function getContenuCours()
{
return $this->contenuCours;
}
/**
* #param string $contenuCours
*/
public function setContenuCours($contenuCours)
{
$this->contenuCours = $contenuCours;
}
}
the twig:
{% for c in cours %}
<div class="col-md-6 col-sm-12">
<article class="cp-taxi-holder cp-deals-holder">
<figure class="cp-thumb">
<img src=" {{ vich_uploader_asset(c, 'imageFile') }}" />
</figure>
<div class="cp-text">
<h3> {{ c.titreCours}}</h3>
<ul class="cp-meta-listed">
<li>Niveau de difficulté <span>moyen</span></li>
</ul>
Voir les lessons
</div>
</article>
</div>
{% endfor %} }}
the controller :
public function AfficheCoursFrontAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$cours = $em->getRepository('DataBundle:CoursCode')->findAll();
/**
* #var $paginator \knp\Component\Pager\paginator
*/
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$cours,
$request->query->getInt('page',1) /*page number*/,
$request->query->getInt('limit',4) /*limit per page*/
);
the form:
class AjoutCoursType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('titreCours')
->add('contenuCours')
->add('imageFile', VichImageType::class, [
'required' => false,])
->add('Ajout',SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DataBundle\Entity\CoursCode'
));
}
symfony is reading the file but doesn't show it
i can't find the problem
The first thing you should do is to inspect your html render and search for the image, then check if src is correct. If the link is correct it's probably a permission error and you should look at the permissions applied to the upload folder web/images/cours.

How do I perform twig result in symfony2?

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?

Symfony and Database

I just make my 2 entity, one is Article and one is Commento, that are comments.
I want a comment form in every single article, so I created the 2 entity, the action in the controller, and the template.
ARTICLE ENTITY
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Article
*
* #ORM\Table()
* #ORM\HasLifecycleCallbacks
* #ORM\Entity
*/
class Article
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titolo", type="string", length=255)
*/
private $titolo;
/**
* #var string
*
* #ORM\Column(name="autore", type="string", length=255)
*/
private $autore;
/**
* #var string
*
* #ORM\Column(name="testo", type="text")
*/
private $testo;
/**
* #var string
*
* #ORM\Column(name="categoria", type="string", length=100)
*/
private $categoria;
/**
* #var string $image
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Perfavore inserisci un'immagine valida!")
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #var date
*
* #ORM\Column(name="data", type="date")
*/
public $data;
/**
* #ORM\OneToMany(targetEntity="Commento", mappedBy="commento")
*/
protected $commento;
public function __construct()
{
$this->commento = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titolo
*
* #param string $titolo
*
* #return Article
*/
public function setTitolo($titolo)
{
$this->titolo = $titolo;
return $this;
}
/**
* Get titolo
*
* #return string
*/
public function getTitolo()
{
return $this->titolo;
}
/**
* Set autore
*
* #param string $autore
*
* #return Article
*/
public function setAutore($autore)
{
$this->autore = $autore;
return $this;
}
/**
* Get autore
*
* #return string
*/
public function getAutore()
{
return $this->autore;
}
/**
* Set testo
*
* #param string $testo
*
* #return Article
*/
public function setTesto($testo)
{
$this->testo = $testo;
return $this;
}
/**
* Get testo
*
* #return string
*/
public function getTesto()
{
return $this->testo;
}
/**
* Set image
*
* #param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
public function getFullImagePath() {
return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../web/imgArticoli/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->image, $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->image);
}
/**
* Set data
*
* #param \DateTime $data
*
* #return Article
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return \DateTime
*/
public function getData()
{
return $this->data;
}
/**
* Set categoria
*
* #param string $categoria
*
* #return Article
*/
public function setCategoria($categoria)
{
$this->categoria = $categoria;
return $this;
}
/**
* Get categoria
*
* #return string
*/
public function getCategoria()
{
return $this->categoria;
}
/**
* Add commento
*
* #param \AppBundle\Entity\Commento $commento
*
* #return Article
*/
public function addCommento(\AppBundle\Entity\Commento $commento)
{
$this->commento[] = $commento;
return $this;
}
/**
* Remove commento
*
* #param \AppBundle\Entity\Commento $commento
*/
public function removeCommento(\AppBundle\Entity\Commento $commento)
{
$this->commento->removeElement($commento);
}
/**
* Get commento
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCommento()
{
return $this->commento;
}
}
COMMENTO ENTITY
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Commento
*
* #ORM\Table()
* #ORM\HasLifecycleCallbacks
* #ORM\Entity
*/
class Commento
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nome", type="string", length=255)
*/
private $nome;
/**
* #var string
*
* #ORM\Column(name="testo", type="text")
*/
private $testo;
/**
* #var datetime
*
* #ORM\Column(name="data", type="datetime")
*/
public $data;
/**
*#ORM\ManyToOne(targetEntity="Article",inversedBy="commenti")
* #ORM\JoinColumn(name="article_id",referencedColumnName="id")
*/
protected $article;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nome
*
* #param string $nome
*
* #return Commento
*/
public function setNome($nome)
{
$this->nome = $nome;
return $this;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
/**
* Set testo
*
* #param string $testo
*
* #return Commento
*/
public function setTesto($testo)
{
$this->testo = $testo;
return $this;
}
/**
* Get testo
*
* #return string
*/
public function getTesto()
{
return $this->testo;
}
/**
* Set data
*
* #param \DateTime $data
*
* #return Commento
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return \DateTime
*/
public function getData()
{
return $this->data;
}
/**
* Set article
*
* #param \AppBundle\Entity\Article $article
* #return Commento
*/
public function setArticle(\AppBundle\Entity\Article $article=null)
{
$this->article = $article;
return $this;
}
/**
* Get article
*
* #return \AppBundle\Entity\Article
*/
public function getArticle()
{
return $this->article;
}
}
ACTIONS IN THE CONTROLLER
public function singlearticleAction(Request $request, $id)
{
//Codice di singlearticle
$art = $this->getDoctrine()->getEntityManager();
$article = $art->getRepository('AppBundle:Article')->find($id);
if (!$article)
{
throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
}
//Fin qui
$commento = new Commento();
$commento->setData(new \DateTime('now'));
$form = $this->createForm(new CommentoType($article), $commento);
$request = $this->getRequest();
$form->handleRequest($request);
if ($form->isValid())
{
if ($article)
{
$commento->setArticle($article);
}
$em = $this->getDoctrine()->getManager();
try
{
$em->persist($commento);
$em->flush();
return $this->redirect('singlearticle');
} catch (\Exception $e)
{
$form->addError(new FormError('errore nel database'));
}
}
return $this->render('default/singlearticle.html.twig', array(
'article' => $article,
'commento' => $commento,
'form' => $form->createView()));
}
public function inserisci_commentoAction(Request $request)/* ROTTA "inserisci_commento" */
{
$commento = new Commento();
$commento->setData(new \DateTime('now'));
$form = $this->createForm(new CommentoType($commento), $commento);
$request = $this->getRequest();
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
try
{
$em->persist($commento);
$em->flush();
return $this->redirect('singlearticle');
} catch (\Exception $e)
{
$form->addError(new FormError('errore nel database'));
}
}
return $this->render('default/singlearticle.html.twig', array(
'commento' => $commento,
'form' => $form->createView()));
}
AND THE TEMPLATE
{% extends 'base.html.twig' %}
{% block body %}{% endblock %}
{% block maincontent %}
<div class="maincontent-title">{{article.titolo}} di {{article.autore}}</div>
<br>
<div class="tipologia">Categoria: {{article.categoria}}</div>
<div class="link" style="float:right;">Modifica</div>
<div class="link" style="float:right;padding-right: 25px;">Elimina</div>
<div class="rigaseparatrice"></div>
<br>
<article>
<p>
{%if article.image is not empty%}
<img class="imgarticolo" src="{{ asset('imgArticoli/' ~ article.id ~'/' ~ article.image)}}"/>
{%endif%}
<div class="titolo"></div>
<br>
<div class="testoarticolo">{{article.testo}}</div>
<br><br>
<br><br>
<div class="form-commento">
INSERISCI UN COMMENTO!
<form action="{{ path('inserisci_commento',{id:commento.id}) }}" method="post" {{ form_enctype(form) }} >
{{ form_errors(form) }}
{{ form_row(form.nome) }}
<br>
{{ form_row(form.testo) }}
<br>
{{ form_rest(form) }}
<input id="bottone" type="submit" value="INSERISCI" />
</form>
</div>
</p>
</article>
{% endblock %}
So, the problem is that when you insert a comment in the form, and I submit the form, I get an error, even if the data are now saved in the db.
Only one data (article_id) that is a Commento's parameter, is NULL, and I don't know why.
This is the error:
No route found for "GET /singlearticle" (from
"http://local/Sito/web/app_dev.php/singlearticle/1")
You need a refactor to the two actions from controller:
public function singlearticleAction($id)
{
//Codice di singlearticle
$art = $this->getDoctrine()->getEntityManager();
$article = $art->getRepository('AppBundle:Article')->find($id);
if (!$article){
throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
}
//Fin qui
$form = $this->createForm(new CommentoType($article), new Commento());
return $this->render('default/singlearticle.html.twig', array(
'article' => $article,
'form' => $form->createView())
);
}
public function inserisci_commentoAction(Request $request, $articleId)
{
//Codice di singlearticle
$em = $this->getDoctrine()->getEntityManager();
$article = $em->getRepository('AppBundle:Article')->find($articleId);
if (!$article) {
throw $this->createNotFoundException('Non riesco a trovare questo articolo!');
}
$commento = new Commento();
$form = $this->createForm(new CommentoType($commento), $commento);
$form->handleRequest($request);
if ($form->isValid())
{
try
{
$commento->setData(new \DateTime('now'));
$commento->setArticle($article);
$em->persist($commento);
$em->flush();
// add a success message to session flashbag
} catch (\Exception $e)
{
// add a error message to session flashbag
}
}
return $this->redirect($this->generateUrl('singlearticle', array('id'=> $articleId)));
}
The route definition for inserisci_commento needs to be changed to:
inserisci_commento:
path: /singlearticle/{articleId}/inserisci_commento
defaults: {_controller: AppBundle:Default:inserisci_commento}
And in twig replace {{ path('inserisci_commento',{id:commento.id}) }} with {{ path('inserisci_commento',{articleId: article.id}) }}
Hope this helps
The problem is in your redirect statement. You need to pass in the article id.
return $this->redirect('singlearticle',array('id' => $article->getId());
whats definetly wrong is the mappedBy attribute in article class
/**
* #ORM\OneToMany(targetEntity="Commento", mappedBy="commento")
*/
protected $commento;
must be
/**
* #ORM\OneToMany(targetEntity="Commento", mappedBy="article")
*/
protected $commento;
and you have a typo in inversedBy attribute in comment class
/**
*#ORM\ManyToOne(targetEntity="Article",inversedBy="commenti")
* #ORM\JoinColumn(name="article_id",referencedColumnName="id")
*/
protected $article;
must be
/**
*#ORM\ManyToOne(targetEntity="Article",inversedBy="commento")
* #ORM\JoinColumn(name="article_id",referencedColumnName="id")
*/
protected $article;

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.

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