Symfony2.7 displaying combox items in twig - 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

Related

Symfony3 - Entities don't work with relations (database with indexes and constraints)

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

count an attribute in an entity

I have an entity "user" that has OneToMany relation with the entity "vehicule". I'm trying to count the number of vehicules for each user. This is my function
$emm = $this->getDoctrine();
$directions = $emm->getRepository('OCUserBundle:User')->findAll();
foreach($directions as $direction) {
$direction->getVehicule()->count();
}
return $this->render('DemandevehBundle:Demande:affiche.html.twig', array('demandes' => $demandes
, ));
but how could I put it in the return so that i could use it in my affiche.html.twig. because I want to show foreach user the number of vehicules he have . Thanks a lot
This is my entity Vehicule
<?php
namespace Car\PfeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use OC\UserBundle\Entity\User;
/**
* Vehicule
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Car\PfeBundle\Entity\VehiculeRepository")
*/
class Vehicule
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="carte_grise", type="integer", unique=true)
*/
private $carteGrise;
/**
* #var string
*
* #ORM\Column(name="modele", type="string", length=255)
*/
private $modele;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=255)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="categorie", type="string", length=255)
*/
private $categorie;
/**
* #var integer
*
* #ORM\Column(name="puissance", type="integer")
*
*/
private $puissance;
/**
* #var integer
*
* #ORM\Column(name="nb_place", type="integer")
*/
private $nbPlace;
/**
* #var integer
*
* #ORM\Column(name="kilometrage", type="integer")
*/
private $kilometrage;
/**
* #var string
*
* #ORM\Column(name="marque", type="string", length=255)
*/
private $marque;
/**
* #var string
*
* #ORM\Column(name="carburant", type="string", length=255)
*/
private $carburant;
/**
* #var string
*
* #ORM\Column(name="transmission", type="string", length=255)
*/
private $transmission;
/**
* #ORM\ManyToOne(targetEntity="OC\UserBundle\Entity\User", inversedBy="vehicule")
* #ORM\JoinColumn(name="User_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $direction;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Id
*
* #param integer $carteGrise
* #return Vehicule
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set carteGrise
*
* #param integer $carteGrise
* #return Vehicule
*/
public function setCarteGrise($carteGrise)
{
$this->carteGrise = $carteGrise;
return $this;
}
/**
* Get carteGrise
*
* #return integer
*/
public function getCarteGrise()
{
return $this->carteGrise;
}
/**
* Set modele
*
* #param string $modele
* #return Vehicule
*/
public function setModele($modele)
{
$this->modele = $modele;
return $this;
}
/**
* Get modele
*
* #return string
*/
public function getModele()
{
return $this->modele;
}
/**
* Set categorie
*
* #param string $categorie
* #return Vehicule
*/
public function setCategorie($categorie)
{
$this->categorie = $categorie;
return $this;
}
/**
* Get categorie
*
* #return string
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set puissance
*
* #param integer $puissance
* #return Vehicule
*/
public function setPuissance($puissance)
{
$this->puissance = $puissance;
return $this;
}
/**
* Get puissance
*
* #return integer
*/
public function getPuissance()
{
return $this->puissance;
}
/**
* Set nbPlace
*
* #param integer $nbPlace
* #return Vehicule
*/
public function setNbPlace($nbPlace)
{
$this->nbPlace = $nbPlace;
return $this;
}
/**
* Get nbPlace
*
* #return integer
*/
public function getNbPlace()
{
return $this->nbPlace;
}
/**
* Set kilometrage
*
* #param integer $kilometrage
* #return Vehicule
*/
public function setKilometrage($kilometrage)
{
$this->kilometrage = $kilometrage;
return $this;
}
/**
* Get kilometrage
*
* #return integer
*/
public function getKilometrage()
{
return $this->kilometrage;
}
/**
* Set marque
*
* #param string $marque
* #return Vehicule
*/
public function setMarque($marque)
{
$this->marque = $marque;
return $this;
}
/**
* Get marque
*
* #return string
*/
public function getMarque()
{
return $this->marque;
}
/**
* Set carburant
*
* #param string $carburant
* #return Vehicule
*/
public function setCarburant($carburant)
{
$this->carburant = $carburant;
return $this;
}
/**
* Get carburant
*
* #return string
*/
public function getCarburant()
{
return $this->carburant;
}
/**
* Set transmission
*
* #param string $transmission
* #return Vehicule
*/
public function setTransmission($transmission)
{
$this->transmission = $transmission;
return $this;
}
/**
* Get transmission
*
* #return string
*/
public function getTransmission()
{
return $this->transmission;
}
public function __toString()
{
return (string)$this->id;
}
/**
* Set type
*
* #param string $type
* #return Vehicule
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set direction
*
* #param \OC\UserBundle\Entity\User $direction
* #return Vehicule
*/
public function setDirection(\OC\UserBundle\Entity\User $direction = null)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return \OC\UserBundle\Entity\User
*/
public function getDirection()
{
return $this->direction;
}
}
and this is my entity User
<?php
namespace OC\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Car\PfeBundle\Entity\Vehicule;
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="OC\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="nomDirec", type="string", length=255, unique=true)
*/
private $nomDirec;
/**
* #var string
*
* #ORM\Column(name="directeur", type="string", length=255)
*/
private $directeur;
/**
* #var string
*
* #ORM\Column(name="adresse", type="string", length=255)
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="fax", type="integer")
*/
private $fax;
/**
* #var string
*
* #ORM\Column(name="tel", type="integer")
*/
private $tel;
/**
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #ORM\Column(name="roles", type="array")
*/
private $roles = array();
/**
* #ORM\OneToMany(targetEntity="Car\PfeBundle\Entity\Vehicule", mappedBy="direction", cascade={"remove", "persist"})
*/
protected $vehicule;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set roles
*
* #param array $roles
* #return User
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return $this->roles;
}
public function eraseCredentials()
{
}
/**
* Set nomDirec
*
* #param string $nomDirec
* #return User
*/
public function setNomDirec($nomDirec)
{
$this->nomDirec = $nomDirec;
return $this;
}
/**
* Get nomDirec
*
* #return string
*/
public function getNomDirec()
{
return $this->nomDirec;
}
/**
* Set directeur
*
* #param string $directeur
* #return User
*/
public function setDirecteur($directeur)
{
$this->directeur = $directeur;
return $this;
}
/**
* Get directeur
*
* #return string
*/
public function getDirecteur()
{
return $this->directeur;
}
/**
* Set adresse
*
* #param string $adresse
* #return User
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set fax
*
* #param \integer $fax
* #return User
*/
public function setFax($fax)
{
$this->fax = $fax;
return $this;
}
/**
* Get fax
*
* #return \integer
*/
public function getFax()
{
return $this->fax;
}
/**
* Set tel
*
* #param integer $tel
* #return User
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return integer
*/
public function getTel()
{
return $this->tel;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
public function __toString()
{
return strval( $this->getId() );
}
/**
* Constructor
*/
public function __construct()
{
$this->vehicule = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add vehicule
*
* #param \Car\PfeBundle\Entity\Vehicule $vehicule
* #return User
*/
public function addVehicule(\Car\PfeBundle\Entity\Vehicule $vehicule)
{
$this->vehicule[] = $vehicule;
return $this;
}
/**
* Remove vehicule
*
* #param \Car\PfeBundle\Entity\Vehicule $vehicule
*/
public function removeVehicule(\Car\PfeBundle\Entity\Vehicule $vehicule)
{
$this->vehicule->removeElement($vehicule);
}
/**
* Get vehicule
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVehicule()
{
return $this->vehicule;
}
}
The correct way to do this in a OOP way , is to define a method that returns the number of vehicules foreach user, so you could to this:
define a getNumberOfVehicules function in your User Class 'Entity'
public function getNumberOfVehicules()
{
return $this->vehicule->count();
}
then in your twig template you just simply call that function , i.e:
{% for user in users %}
<p>{{user.username}} {{user.getNumberOfVehicules()}}</p>
{% endfor %}
to get the desired result, I would do something like this ( haven't tested the query, but it should pretty much work )
$em = $this->getDoctrine();
$userRepository = $em->getRepository('OCUserBundle:User');
$qb = $userRepository->createQueryBuilder('user')
->leftJoin('user.vehicule','vehicule')
->addSelect('COUNT(vehicule.id) AS vehicule_count')
->groupBy('user.id')
->getQuery();
$result = $qb->getResult();
Pass the result to the view
return $this->render('DemandevehBundle:Demande:affiche.html.twig',
array('demandes' => $result ));
In the view you can iterate over the results.
$qb = $this->getEntityManager()->createQueryBuilder();
return $qb->select('u.username as name, count(v.id) as count')
->from('OCUserBundle:User', 'u')
->leftJoin('u.vehicule', 'v')
->groupBy('u.id')
->getQuery()
->getResult();
Here we get an array as result with each user plus no of corresponding vehicles.Just pass result to twig and then foreach name and count.All the best.

Sonata AdminBundle, get the parameter of an entity

I have an entity Prototype with a relation many to one with project and I want to override a function in the CRUDController.
Here is the code :
$idPrototype = $this->get('request')->get($this->admin->getIdParameter());
I get the id of the prototype, but I want the parameter 'project' ( the id of the project )
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;
private $projet;
public function __construct()
{
$this->dateCreation = new \DateTime("now");
$this->nom = "";
$this->description = " ";
}
/**
* 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;
}
}
I've tried to use ModelManager() but I get this error "Attempted to call an undefined method named "getModelManager" of class "AppBundle\Controller\CRUDProtoController". "
I'm new with sonata and symfony and I find difficulties with it.

Error trying flush an object in the database with Symfony2

I am new in Symfony2 (worked with Symfony 1 for several years) and I am trying to insert some records in a Entity with a relationship to another Entity, here are them:
<?php
namespace Jjj\SomeBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
/**
* Jjj\SomeBundle\Entity
*
* #ORM\Table(name="content")
* #ORM\Entity(repositoryClass="Jjj\SomeBundle\Entity\ContentRepository")
*/
class Content implements Translatable
{
/**
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="contents")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category_id;
/**
* #Gedmo\Translatable
* #ORM\Column(name="title", type="string", length=32, nullable=false)
*/
protected $title;
/**
* #Gedmo\Translatable
* #ORM\Column(name="summary", type="text", nullable=true)
*/
protected $summary;
/**
* #Gedmo\Translatable
* #ORM\Column(name="fulltext", type="text", nullable=true)
*/
protected $fulltext;
/**
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
*/
protected $created_at;
/**
*
* #ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
protected $updated_at;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(length=128, unique=true)
*/
private $slug;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category_id
*
* #param integer $categoryId
* #return Content
*/
public function setCategoryId($categoryId)
{
$this->category_id = $categoryId;
return $this;
}
/**
* Get category_id
*
* #return integer
*/
public function getCategoryId()
{
return $this->category_id;
}
/**
* Set title
*
* #param string $title
* #return Content
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set slug
*
* #param string $slug
* #return Content
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set summary
*
* #param string $summary
* #return Content
*/
public function setSummary($summary)
{
$this->summary = $summary;
return $this;
}
/**
* Get summary
*
* #return string
*/
public function getSummary()
{
return $this->summary;
}
/**
* Set fulltext
*
* #param string $fulltext
* #return Content
*/
public function setFulltext($fulltext)
{
$this->fulltext = $fulltext;
return $this;
}
/**
* Get fulltext
*
* #return string
*/
public function getFulltext()
{
return $this->fulltext;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Content
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Content
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
}
This is the Category Entity:
<?php
namespace Jjj\SomeBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* Jjj\SomeBundle\Entity
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="Jjj\SomeBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=32, nullable=false)
*/
protected $title;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
protected $created_at;
/**
* #var string
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false)
*/
protected $updated_at;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(length=128, unique=true)
*/
private $slug;
/**
* #ORM\OneToMany(targetEntity="Content", mappedBy="category")
*/
protected $contents;
public function __construct()
{
$this->contents = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Category
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Category
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Category
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set slug
*
* #param string $slug
* #return Category
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Add contents
*
* #param \Jaguar\AloBundle\Entity\Content $contents
* #return Category
*/
public function addContent(\Jaguar\AloBundle\Entity\Content $contents)
{
$this->contents[] = $contents;
return $this;
}
/**
* Remove contents
*
* #param \Jjj\SomeBundle\Entity\Content $contents
*/
public function removeContent(\Jjj\SomeBundle\Entity\Content $contents)
{
$this->contents->removeElement($contents);
}
/**
* Get contents
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContents()
{
return $this->contents;
}
}
In the controller that is running, I wrote this:
$content = new Content();
$content->setTitle('Content Example');
$content->setSummary('Content Example');
$content->setFulltext('My first content...');
$content->setCategoryId(2);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($content);
$em->flush();
The error says:
ContextErrorException: Warning: spl_object_hash() expects parameter 1 to be object, integer given in D:\xampp\htdocs\projects\alopatria\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 1367
I was googling for a while but no luck found.
Any help, please?
Thanks!
You’re doing the mapping in Content.php in the wrong way.
If you’re setting a ManyToOne relation with the Category Entity, you should have a $category and not a $category_id attribute. You should deal with objects, and not integers.
Therefore, your Content Entity should look like this:
<?php
// Jjj\SomeBundle\Entity\Content.php
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="contents")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* Set category
*
* #param \Jjj\SomeBundle\Entity\Category $category
* #return Content
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return category
*/
public function getCategory()
{
return $this->category;
}
And your controller like this:
<?php
$category = new Category();
//… $category->setTitle() and so on…
$content = new Content();
$content->setTitle('Content Example');
$content->setSummary('Content Example');
$content->setFulltext('My first content...');
$content->setCategory($category);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($category);
$em->persist($content);
$em->flush();
You will then be able to access the id of a Category Entity (already fetched from database) with:
$categoryId = $category->getId();

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