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 %}
Related
Starring for this for several hours now, maybe I missed something obvious.
Have this database structure (with indexes, and constraints)
CREATE TABLE `exploit` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`edb_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`date` datetime not null,
`author` bigint(20) not null ,
`name` varchar(255) not null,
`category` bigint(20) not null,
`version` varchar(255) not null,
`type` bigint(20) not null,
`content` longtext COLLATE utf8_unicode_ci NOT NULL,
`dork` varchar(255) null,
`software_link` varchar(255) null,
`tested_on` varchar(255) null,
PRIMARY KEY (`id`),
KEY `exploit_category_idx` (`category`),
KEY `exploit_type_idx` (`type`),
KEY `exploit_author_idx` (`author`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `category_name_id_idx` (`id`),
CONSTRAINT `category_name_id` FOREIGN KEY (`id`) REFERENCES `exploit` (`category`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `type` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `type_name_id_idx` (`id`),
CONSTRAINT `type_name_id` FOREIGN KEY (`id`) REFERENCES `exploit` (`type`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `author` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `author_name_id_idx` (`id`),
CONSTRAINT `author_name_id` FOREIGN KEY (`id`) REFERENCES `exploit` (`author`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Created these entities:
::::::::::::::
Author.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* Author
*
* #ORM\Table(name="author", indexes={#ORM\Index(name="author_name_id_idx", columns={"id"})})
* #ORM\Entity
*/
class Author
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", author="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Exploit", mappedBy="author", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="exploits", referencedColumnName="id")
*/
private $exploits;
/**
* Author constructor.
*/
public function __construct()
{
$this->exploits = new ArrayCollection();
}
/**
* Set name
*
* #param string $name
*
* #return Author
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get id
*
*/
public function getId()
{
return $this->id;
}
public function __toString()
{
return $this->name;
}
/**
* #param Exploits $exploit
*
* #return Author
*/
public function addExploit($exploit)
{
$this->exploits->add($exploit);
return $this;
}
/**
* #param Collection $exploits
*
* #return Author
*/
public function setExploits(Collection $exploits)
{
$this->exploits->clear();
foreach ($exploits as $exploit) {
$exploit->add($this);
}
$this->exploits = $exploits;
return $this;
}
}
::::::::::::::
Category.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* Category
*
* #ORM\Table(name="category", indexes={#ORM\Index(name="category_name_id_idx", columns={"id"})})
* #ORM\Entity
*/
class Category
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", category="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Exploit", mappedBy="category", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="exploits", referencedColumnName="id")
*/
private $exploits;
/**
* Author constructor.
*/
public function __construct()
{
$this->exploits = new ArrayCollection();
}
/**
* Set name
*
* #param string $name
*
* #return Author
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get id
*
*/
public function getId()
{
return $this->id;
}
public function __toString()
{
return $this->name;
}
/**
* #param Exploits $exploit
*
* #return Author
*/
public function addExploit($exploit)
{
$this->exploits->add($exploit);
return $this;
}
/**
* #param Collection $exploits
*
* #return Author
*/
public function setExploits(Collection $exploits)
{
$this->exploits->clear();
foreach ($exploits as $exploit) {
$exploit->add($this);
}
$this->exploits = $exploits;
return $this;
}
}
::::::::::::::
Exploit.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Author;
use AppBundle\Entity\Type;
use AppBundle\Entity\Category;
/**
* Exploit
*
* #ORM\Table(name="exploit", indexes={#ORM\Index(name=exploit_category_idx", columns={"category"}), #ORM\Index(name="exploit_type_idx", columns={"type"}), #ORM\Index(name="exploit_author_idx", columns={"
author"})})
*/
class Exploit
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="edb_id", type="string", length=100, nullable=false)
*/
private $edbId;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Author", inversedBy="exploits")
* #ORM\JoinColumn(name="author", referencedColumnName="id")
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Category", inversedBy="exploits")
* #ORM\JoinColumn(name="category", referencedColumnName="id")
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=255, nullable=false)
*/
private $version;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", inversedBy="exploits")
* #ORM\JoinColumn(name="type", referencedColumnName="id")
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* #var string
*
* #ORM\Column(name="dork", type="string", length=255, nullable=true)
*/
private $dork;
/**
* #var string
*
* #ORM\Column(name="software_link", type="string", length=255, nullable=true)
*/
private $softwareLink;
/**
* #var string
*
* #ORM\Column(name="tested_on", type="string", length=255, nullable=true)
*/
private $testedOn;
/**
* Set edbId
*
* #param integer $edbId
*
* #return Exploit
*/
public function setEdbId($edbId)
{
$this->edbId = $edbId;
return $this;
}
/**
* Get edbId
*
* #return integer
*/
public function getEdbId()
{
return $this->edbId;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Exploit
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set author
*
* #param integer $author
*
* #return Exploit
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return integer
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set name
*
* #param string $name
*
* #return Exploit
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set category
*
* #param integer $category
*
* #return Exploit
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return integer
*/
public function getCategory()
{
return $this->category;
}
/**
* Set version
*
* #param string $version
*
* #return Exploit
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Get version
*
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Set type
*
* #param integer $type
*
* #return Exploit
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType()
{
return $this->type;
}
/**
* Set content
*
* #param string $content
*
* #return Exploit
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set dork
*
* #param string $dork
*
* #return Exploit
*/
public function setDork($dork)
{
$this->dork = $dork;
return $this;
}
/**
* Get dork
*
* #return string
*/
public function getDork()
{
return $this->dork;
}
/**
* Set softwareLink
*
* #param string $softwareLink
*
* #return Exploit
*/
public function setSoftwareLink($softwareLink)
{
$this->softwareLink = $softwareLink;
return $this;
}
/**
* Get softwareLink
*
* #return string
*/
public function getSoftwareLink()
{
return $this->softwareLink;
}
/**
* Set testedOn
*
* #param string $testedOn
*
* #return Exploit
*/
public function setTestedOn($testedOn)
{
$this->testedOn = $testedOn;
return $this;
}
/**
* Get testedOn
*
* #return string
*/
public function getTestedOn()
{
return $this->testedOn;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
::::::::::::::
Type.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* Type
*
* #ORM\Table(name="type", indexes={#ORM\Index(name="type_name_id_idx", columns={"id"})})
* #ORM\Entity
*/
class Type
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Exploit", mappedBy="type", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="exploits", referencedColumnName="id")
*/
private $exploits;
/**
* Type constructor.
*/
public function __construct()
{
$this->exploits = new ArrayCollection();
}
/**
* Set name
*
* #param string $name
*
* #return Type
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get id
*
*/
public function getId()
{
return $this->id;
}
public function __toString()
{
return $this->name;
}
/**
* #param Exploits $exploit
*
* #return Type
*/
public function addExploit($exploit)
{
$this->exploits->add($exploit);
return $this;
}
/**
* #param Collection $exploits
*
* #return Type
*/
public function setExploits(Collection $exploits)
{
$this->exploits->clear();
foreach ($exploits as $exploit) {
$exploit->add($this);
}
$this->exploits = $exploits;
return $this;
}
}
but somehow when I make a query I get, like:
$exploits = $this->getDoctrine()
->getRepository('AppBundle:Exploit')
->findAll();
and in view
<th scope="row"> {{ exploit.id }} </th>
<td> {{ exploit.name }} </td>
<td> {{ exploit.author.name }} </td>
<td> {{ exploit.type.name }} </td>
<td> {{ exploit.category.name }} </td>
<td>{{ exploit.date|date('F j, Y, g:i a') }}</td>
I get this error:
Impossible to access an attribute ("name") on a integer variable ("1").
Any good soul can look into this and try to reproduce it?
MySQL Dump to recreate the tables with content is here:
https://0bin.net/paste/2tV3MEw4A2tdAVsR#R3rBNW4seWkK9HtlJFwbsA6+RmhhWPilm40L8QfeiTp
Thanks!
It says it right there, you're trying to access the name attribute of something, but that something isn't an object. Its a 1.
You access .name several times so unsure which one of these it is without more info and a line number
<th scope="row"> {{ exploit.id }} </th>
<td> {{ exploit.name }} </td>
<td> {{ exploit.author.name }} </td>
<td> {{ exploit.type.name }} </td>
<td> {{ exploit.category.name }} </td>
<td>{{ exploit.date|date('F j, Y, g:i a') }}</td>
</th>
But if we assume its Author then its clear that the getAuthor() method returns a bigint.
How did you get that entity code and the database code? Because they do not look correct, they are getting and setting integers, rather than objects.
UPDATE
Generate entities with
php bin/console doctrine:generate:entities AppBundle
View the SQL using
php bin/console doctrine:schema:update --dump-sql
Execute the SQL using
php bin/console doctrine:schema:update --force
Got it working with these entities:
::::::::::::::
Author.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* User
*
* #ORM\Table(name="author")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class Author
{
/**
* #var integer
*
* #ORM\Column(name="a_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $a_id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Exploit", mappedBy="author")
*/
protected $exploits;
public function __construct()
{
$this->exploits = new ArrayCollection();
}
public function addExploit(\AppBundle\Entity\Exploit $exploit)
{
$this->report[] = $exploit;
}
public function getExploits()
{
return $this->exploits;
}
/**
* Set name
*
* #param string $name
*
* #return Type
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
::::::::::::::
Category.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="c_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $c_id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Exploit", mappedBy="category")
*/
protected $exploits;
public function __construct()
{
$this->exploits = new ArrayCollection();
}
public function addExploit(\AppBundle\Entity\Exploit $exploit)
{
$this->report[] = $exploit;
}
public function getExploits()
{
return $this->exploits;
}
/**
* Set name
*
* #param string $name
*
* #return Type
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
::::::::::::::
Exploit.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Author;
/**
* Exploit
*
* #ORM\Table(name="exploit")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ReportRepository")
*/
class Exploit
{
/**
* #var integer
*
* #ORM\Column(name="e_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $e_id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Author", inversedBy="exploi
ts")
* #ORM\JoinColumn(name="author_id", referencedColumnName="a_id")
*/
protected $author;
public function setAuthor(\AppBundle\Entity\Author $author)
{
$this->author = $author;
}
public function getAuthor()
{
return $this->author;
}
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Category", inversedBy="expl
oits")
* #ORM\JoinColumn(name="category_id", referencedColumnName="c_id")
*/
protected $category;
public function setCategory(\AppBundle\Entity\Category $category)
{
$this->category = $category;
}
public function getCategory()
{
return $this->category;
}
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", inversedBy="exploits
")
* #ORM\JoinColumn(name="type_id", referencedColumnName="t_id")
*/
protected $type;
public function setType(\AppBundle\Entity\Type $type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
/**
* #var string
*
* #ORM\Column(name="edb_id", type="string", length=100, nullable=false)
*/
private $edbId;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=255, nullable=false)
*/
private $version;
/**
* #var string
*
* #ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* #var string
*
* #ORM\Column(name="dork", type="string", length=255, nullable=true)
*/
private $dork;
/**
* #var string
*
* #ORM\Column(name="software_link", type="string", length=255, nullable=tru
e)
*/
private $softwareLink;
/**
* #var string
*
* #ORM\Column(name="tested_on", type="string", length=255, nullable=true)
*/
private $testedOn;
/**
* Set edbId
*
* #param integer $edbId
*
* #return Exploit
*/
public function setEdbId($edbId)
{
$this->edbId = $edbId;
return $this;
}
/**
* Get edbId
*
* #return integer
*/
public function getEdbId()
{
return $this->edbId;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Exploit
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set name
*
* #param string $name
*
* #return Exploit
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set version
*
* #param string $version
*
* #return Exploit
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Get version
*
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Set content
*
* #param string $content
*
* #return Exploit
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set dork
*
* #param string $dork
*
* #return Exploit
*/
public function setDork($dork)
{
$this->dork = $dork;
return $this;
}
/**
* Get dork
*
* #return string
*/
public function getDork()
{
return $this->dork;
}
/**
* Set softwareLink
*
* #param string $softwareLink
*
* #return Exploit
*/
public function setSoftwareLink($softwareLink)
{
$this->softwareLink = $softwareLink;
return $this;
}
/**
* Get softwareLink
*
* #return string
*/
public function getSoftwareLink()
{
return $this->softwareLink;
}
/**
* Set testedOn
*
* #param string $testedOn
*
* #return Exploit
*/
public function setTestedOn($testedOn)
{
$this->testedOn = $testedOn;
return $this;
}
/**
* Get testedOn
*
* #return string
*/
public function getTestedOn()
{
return $this->testedOn;
}
/**
* Get e_id
*
* #return integer
*/
public function gete_id()
{
return $this->e_id;
}
}
::::::::::::::
Type.php
::::::::::::::
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exploit;
/**
* Type
*
* #ORM\Table(name="type")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TypeRepository")
*/
class Type
{
/**
* #var integer
*
* #ORM\Column(name="t_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $t_id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Exploit", mappedBy="type")
*/
protected $exploits;
public function __construct()
{
$this->exploits = new ArrayCollection();
}
public function addExploit(\AppBundle\Entity\Exploit $exploit)
{
$this->report[] = $exploit;
}
public function getExploits()
{
return $this->exploits;
}
/**
* Set name
*
* #param string $name
*
* #return Type
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
This view:
{% for exploit in exploits %}
<tr>
<th scope="row">{{ exploit.e_id }}</th>
<td>{{ exploit.name }}</td>
<td> {{ exploit.author.name }} </td>
<td> {{ exploit.category.name }} </td>
<td> {{ exploit.type.name }} </td>
<td>
View
Edit
Delete
</td>
</tr>
{% endfor %}
And controller:
$exploits = $this->getDoctrine()
->getRepository('AppBundle:Exploit')
->findAll();
return $this->render('exploit/index.html.twig', array(
'exploits' => $exploits
));
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?
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
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.
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 !