Failed to create object. Many-To-Many relation - php

I have a problem with my code. It's about a restaurant. I have two objects with a Many-To-Many relation: Products and Days. When I try to create a Day, I receive this error: "Failed to create object: App\Entity\Day\Day". Where am I wrong?
I put the code for entities here. If you need more just tell me. I don't think that it is from admin part.
Here is the Product entity:
<?php
namespace App\Entity\Product;
use App\Entity\Category\Category;
use App\Entity\Day\Day;
use App\Entity\ProductEntry\ProductEntry;
use App\Entity\Restaurant\Restaurant;
use App\Entity\Schedule\Schedule;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
/**
* Class Product
* #ORM\Entity(repositoryClass="App\Repository\Product\ProductRepository")
* #ORM\Table(name="products")
* #package App\Entity\Product
*/
class Product
{
/**
* #var int
*
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="added_date", type="datetime", nullable=false)
*/
private $addedDate;
/**
* #var boolean
*
* #ORM\Column(name="availability", type="boolean", nullable=true)
*/
private $availability;
/**
* #var Category
*
* #ORM\ManyToOne(targetEntity="App\Entity\Category\Category", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
private $category;
/**
* #var float
*
* #ORM\Column(name="price", type="float", length=255, nullable=true)
*/
private $price;
/**
* #var ProductEntry
*
* #ORM\OneToMany(targetEntity="App\Entity\ProductEntry\ProductEntry", mappedBy="originalProduct", cascade={"persist"})
* #Serializer\Exclude()
*/
private $productsEntries;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Schedule\Schedule", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(name="schedule_id", referencedColumnName="id", onDelete="CASCADE")
*
* #var Schedule
*/
private $schedule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Restaurant\Restaurant", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(name="restaurant_id", referencedColumnName="id", onDelete="CASCADE")
*
* #var Restaurant
*/
private $restaurant;
/**
* #var Day
*
* #ORM\ManyToMany(targetEntity="App\Entity\Day\Day", mappedBy="products", cascade={"persist"})
*/
private $days;
public function __toString()
{
return $this->name ?: "";
}
public function __construct()
{
$this->addedDate = new \DateTime();
$this->days = new ArrayCollection();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id)
{
$this->id = $id;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param string $name
*/
public function setName(string $name)
{
$this->name = $name;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription(string $description)
{
$this->description = $description;
}
/**
* #return mixed
*/
public function getAddedDate()
{
return $this->addedDate;
}
/**
* #param mixed $addedDate
*/
public function setAddedDate($addedDate)
{
$this->addedDate = $addedDate;
}
/**
* #return bool
*/
public function isAvailability()
{
return $this->availability;
}
/**
* #param bool $availability
*/
public function setAvailability($availability)
{
$this->availability = $availability;
}
/**
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* #param float $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return Category
*/
public function getCategory()
{
return $this->category;
}
/**
* #param Category $category
*/
public function setCategory($category): void
{
$this->category = $category;
}
/**
* #return ProductEntry
*/
public function getProductsEntries()
{
return $this->productsEntries;
}
/**
* #param ProductEntry $productsEntries
*/
public function setProductsEntries(ProductEntry $productsEntries): void
{
$this->productsEntries = $productsEntries;
}
/**
* #return Schedule
*/
public function getSchedule()
{
return $this->schedule;
}
/**
* #param Schedule $schedule
*/
public function setSchedule(Schedule $schedule): void
{
$this->schedule = $schedule;
}
/**
* #return Restaurant
*/
public function getRestaurant()
{
return $this->restaurant;
}
/**
* #param Restaurant $restaurant
*/
public function setRestaurant(Restaurant $restaurant): void
{
$this->restaurant = $restaurant;
}
/**
* #return Day
*/
public function getDays()
{
return $this->days;
}
/**
* #param Day $days
*/
public function setDays(Day $days): void
{
$this->days = $days;
}
}
Here is Day entity:
<?php
namespace App\Entity\Day;
use App\Entity\Product\Product;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Day
* #package App\Entity\Day
* #ORM\Entity(repositoryClass="App\Repository\Day\DayRepository")
* #ORM\Table(name="days")
*/
class Day
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", nullable=false)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="current_date", type="datetime", nullable=false)
*/
private $currentDate;
/**
* #var \DateTime
*
* #ORM\Column(name="max_date", type="datetime", nullable=true)
*/
private $maxDate;
/**
* #var Product
*
* #ORM\ManyToMany(targetEntity="App\Entity\Product\Product", inversedBy="days", cascade={"persist"})
* #ORM\JoinTable(name="product_day",
* joinColumns={#ORM\JoinColumn(name="day_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id")})
*/
private $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* #return \DateTime
*/
public function getCurrentDate()
{
return $this->currentDate;
}
/**
* #param \DateTime $currentDate
*/
public function setCurrentDate(\DateTime $currentDate): void
{
$this->currentDate = $currentDate;
}
/**
* #return \DateTime
*/
public function getMaxDate()
{
return $this->maxDate;
}
/**
* #param \DateTime $maxDate
*/
public function setMaxDate(\DateTime $maxDate): void
{
$this->maxDate = $maxDate;
}
/**
* #return Product
*/
public function getProducts()
{
return $this->products;
}
/**
* #param Product $products
*/
public function setProducts(Product $products): void
{
$this->products = $products;
}
}

It seems that you created a column for your Day Entity that is called current_date
/**
* #var \DateTime
*
* #ORM\Column(name="current_date", type="datetime", nullable=false)
*/
private $currentDate;
If you are using MySQL, current_date is a reserved word. Please check https://dev.mysql.com/doc/refman/5.5/en/keywords.html for further reference.

Like Vincent said in comment, your namespaces are fishy...
Unless you really placed them in a sub-folder, it should be namespace App\Entity
In Product entity you can shorten you JoinColumn for some parameters.
Unless you really need something specific, you don't need to write that much. Symfony have 'default' values.
Also, you don't add #var on a mapping. Symfony will take is as a parameter only instead of mapping.
/**
* #var Category
*
* #ORM\ManyToOne(targetEntity="App\Entity\Category\Category", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(onDelete="CASCADE", nullable=true)
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Schedule\Schedule", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(onDelete="CASCADE")
*/
private $schedule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Restaurant\Restaurant", inversedBy="products", cascade={"persist"})
* #ORM\JoinColumn(onDelete="CASCADE")
*/
private $restaurant;
The same apply to your Day entity.
/**
* #var Product
*
* #ORM\ManyToMany(targetEntity="App\Entity\Product\Product", inversedBy="days", cascade={"persist"})
* #ORM\JoinTable(name="product_day")
*/
private $products;
Doing so will prevent you to make some smalls mapping errors.
Try to correct those points first, then let us know if you still have your problem.

Related

Symfony elastica mapping with relationsip causing OutOfMemoryException while populating the index

I wanted to index some data from a associated entity of the main entity which I already have an index for. My mapping rules are as below and I have given the 2 entities below too. My problem is I am getting OutOfMemoryException while trying to populate the index. bin/console fos:elastica:populate --index=sales_rule
Index configuration
sales_rule:
client: default
use_alias: true
types:
sales_rule:
mappings:
id: {type: integer}
name:
description:
salesCoupons:
type: nested
properties:
code:
persistence:
driver: orm
model: MyProject\MyBundle\Entity\SalesRule
provider:
batch_size: 100
listener:
Entities
/**
* #ORM\Table(name="sales_rule")
* #ORM\Entity(repositoryClass="MyProject\MyBundle\Repository\SalesRuleRepository")
*/
class SalesRule
{
/**
* #var int
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $name;
/**
* #var string
*
* #ORM\Column(type="text")
*/
private $description;
/**
* #var int
*
* #ORM\Column(type="integer", nullable=true)
*/
private $usageLimit;
/**
* #var SalesCoupon[]|ArrayCollection
*
* #ORM\OneToMany(targetEntity="SalesCoupon", mappedBy="salesRule")
*/
private $salesCoupons;
public function __construct()
{
$this->salesCoupons = new ArrayCollection();
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return int
*/
public function getUsageLimit()
{
return $this->usageLimit;
}
/**
* #return int
*/
public function getUsagePerCustomer()
{
return $this->usagePerCustomer;
}
/**
* #param string $description
* #return SalesRule
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #param string $name
* #return SalesRule
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #param int $usageLimit
* #return SalesRule
*/
public function setUsageLimit($usageLimit)
{
$this->usageLimit = $usageLimit;
return $this;
}
/**
* #return SalesCoupon[]|ArrayCollection
*/
public function getSalesCoupons()
{
return $this->salesCoupons;
}
/**
* #param ArrayCollection $salesCoupons
*/
public function setSalesCoupons(ArrayCollection $salesCoupons)
{
$this->salesCoupons = $salesCoupons;
}
}
/**
* #ORM\Table(name="sales_coupon")
* #ORM\Entity(repositoryClass="MyProject\MyBundle\Repository\SalesCouponRepository")
*/
class SalesCoupon
{
/**
* #var int
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
private $id;
/**
* #var SalesRule
*
* #Serializer\Exclude
*
* #ORM\ManyToOne(targetEntity="SalesRule", inversedBy="salesCoupons")
* #ORM\JoinColumn(nullable=false)
*/
private $salesRule;
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $fromDate;
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $toDate;
/**
* #var string
*
* #ORM\Column(nullable=true)
*/
private $code;
/**
* #var int
*
* #Assert\Range(min=0)
*
* #ORM\Column(type="integer", nullable=true)
*/
private $usageLimit;
public function __construct()
{
$this->salesCouponCustomers = new ArrayCollection();
}
/**
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* #return \DateTime
*/
public function getFromDate()
{
return $this->fromDate;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #return \Unity\CmsBundle\Entity\SalesRule
*/
public function getSalesRule()
{
return $this->salesRule;
}
/**
* #return \DateTime
*/
public function getToDate()
{
return $this->toDate;
}
/**
* #param string $code
* #return SalesCoupon
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #param \DateTime $fromDate
* #return SalesCoupon
*/
public function setFromDate($fromDate)
{
$this->fromDate = $fromDate;
return $this;
}
/**
* #param \Unity\CmsBundle\Entity\SalesRule $salesRule
* #return SalesCoupon
*/
public function setSalesRule(SalesRule $salesRule)
{
$this->salesRule = $salesRule;
return $this;
}
/**
* #param \DateTime $toDate
* #return SalesCoupon
*/
public function setToDate($toDate)
{
$this->toDate = $toDate;
return $this;
}
}
Can you try set limit memory unlimit.
php -d memory_limit=-1 bin/console fos:elastica:populate --index=sales_rule

Why my symfony entity is not managed?

I have a Portfolio entity which is working well to create or update but I can't delete it. Symfony throws this error:
Entity matthieu-appriou is not managed. An entity is managed if its
fetched from the database or registered as new through
EntityManager#persist
Here is my entity:
<?php
namespace CreasensoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SensoBundle\Entity\Talent;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use JMS\Serializer\Annotation\MaxDepth;
use JMS\Serializer\Annotation\Exclude;
/**
* Portfolio
*
* #ORM\Entity
* #ORM\Table(name="portfolio")
* #ORM\Entity(repositoryClass="CreasensoBundle\Repository\PortfolioRepository")
*/
class Portfolio
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean", nullable=true)
*/
private $visible;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Talent", cascade={"persist", "remove"}, inversedBy="portfolio")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $talent;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Image", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $image;
/**
* #var string
*
* #ORM\Column(name="folio_label", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $folioLabel;
/**
* #var string
*
* #ORM\Column(name="main_customers", type="string", length=400, nullable=true)
*/
private $mainCustomers;
/**
* #var string
*
* #ORM\Column(name="main_agencies", type="string", length=400, nullable=true)
*/
private $mainAgencies;
/**
* #var string
*
* #ORM\Column(name="publications", type="string", length=700, nullable=true)
*/
private $publications;
/**
* #var string
*
* #ORM\Column(name="description_title", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $descriptionTitle;
/**
* #var string
*
* #ORM\Column(name="description_content", type="text", nullable=true)
* #Gedmo\Translatable
*/
private $descriptionText;
/**
* #MaxDepth(2)
* #ORM\ManyToMany(targetEntity="SensoBundle\Entity\Expertise", cascade={"persist"})
*/
private $expertises;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var \DateTime $updated
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $mostRecentProjectDate;
/**
* #var \DateTime $featuredTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $featuredTime;
/**
* #var \DateTime $submissionTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $submissionTime;
/**
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->setVisible(false);
$this->expertises = new ArrayCollection();
}
public function __toString() {
return $this->getSlug();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
public function getSlug()
{
return $this->getTalent()->getSlug();
}
/**
* Set visible
*
* #param boolean $visible
*
* #return Portfolio
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getTalent()
{
return $this->talent;
}
/**
* #param mixed $talent
*/
public function setTalent($talent)
{
$this->talent = $talent;
$talent->setPortfolio($this);
}
/**
* #return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* #param mixed $image
*/
public function setImage($image)
{
if ($image) {
$image->setParentType('portfolio');
}
$this->image = $image;
}
/**
* #return string
*/
public function getMainCustomers()
{
return $this->mainCustomers;
}
/**
* #param string $mainCustomers
*/
public function setMainCustomers($mainCustomers)
{
$this->mainCustomers = $mainCustomers;
}
/**
* #return string
*/
public function getMainAgencies()
{
return $this->mainAgencies;
}
/**
* #param string $mainAgencies
*/
public function setMainAgencies($mainAgencies)
{
$this->mainAgencies = $mainAgencies;
}
/**
* #return string
*/
public function getDescriptionTitle()
{
return $this->descriptionTitle;
}
/**
* #param string $descriptionTitle
*/
public function setDescriptionTitle($descriptionTitle)
{
$this->descriptionTitle = $descriptionTitle;
}
/**
* #return string
*/
public function getDescriptionText()
{
return $this->descriptionText;
}
/**
* #param string $descriptionText
*/
public function setDescriptionText($descriptionText)
{
$this->descriptionText = $descriptionText;
}
public function addExpertise($expertise)
{
$this->expertises[] = $expertise;
return $this;
}
public function removeExpertise($expertise)
{
$this->expertises->removeElement($expertise);
}
public function getExpertises()
{
return $this->expertises;
}
public function setExpertises($expertises)
{
$this->expertises = $expertises;
}
/**
* #return mixed
*/
public function getCreated()
{
return $this->created;
}
/**
* #param mixed $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #param \DateTime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* #return \DateTime
*/
public function getFeaturedTime()
{
return $this->featuredTime;
}
/**
* #param \DateTime $featuredTime
*/
public function setFeaturedTime($featuredTime)
{
$this->featuredTime = $featuredTime;
}
/**
* #return string
*/
public function getPublications()
{
return $this->publications;
}
/**
* #param string $publications
*/
public function setPublications($publications)
{
$this->publications = $publications;
}
/**
* #return mixed
*/
public function getSubmissionTime()
{
return $this->submissionTime;
}
/**
* #param mixed $submissionTime
*/
public function setSubmissionTime($submissionTime)
{
$this->submissionTime = $submissionTime;
}
/**
* #return string
*/
public function getFolioLabel()
{
return $this->folioLabel;
}
/**
* #param string $folioLabel
*/
public function setFolioLabel($folioLabel)
{
$this->folioLabel = $folioLabel;
}
public function getType()
{
return 'portfolio';
}
/**
* #return \DateTime
*/
public function getMostRecentProjectDate()
{
return $this->mostRecentProjectDate;
}
/**
* #param \DateTime $mostRecentProjectDate
*/
public function setMostRecentProjectDate($mostRecentProjectDate)
{
$this->mostRecentProjectDate = $mostRecentProjectDate;
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
}
And here is the code sample I use to reproduce this error:
<?php
// namespace and use ...
/**
* Tool controller.
*
* #Route("/admin/test")
*/
class TestController extends Controller
{
/**
*
* #Route("/testTwo", name="testTwo")
* #Method({"GET", "POST"})
*/
public function indexTwoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$pr = $this->get('creasenso.portfolio_repo');
$p = $pr->find(32);
$em->remove($p);
$em->flush();
return new Response("<html><head></head><body><hr />Done</body></html>");
}
}
Here is the repository linked to this entity:
<?php
namespace CreasensoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* PortfolioRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PortfolioRepository extends EntityRepository
{
protected $qb;
public function init()
{
$this->qb = $this->createQueryBuilder('p');
}
public function isVisible()
{
$this->qb
->andWhere('p.visible = :visible')
->setParameter(':visible', 1);
}
public function getAllPublicPortfolioCount()
{
$this->init();
$this->isVisible();
$this->qb->select('COUNT(p)');
return $this->qb->getQuery()->getSingleScalarResult();
}
public function getQueryBuilder()
{
return $this->qb;
}
}
Do you have any clue about this behavior? Thank you very much.
You are getting your repository directly from the service container when you should be getting it from your EntityManager through getRepository().
You are not loading your entity from the entityManager that you flush so it is not managed

Symfony2 wrong instance passed with twig extension

I created a Twig extension, registered it in services, but im getting an error:
This is the extension:
<?php
// src/AppBundle/Twig/AppExtension.php
namespace Mp\ShopBundle\twig;
class AppExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
'getTotalPrice' => new \Twig_Function_Method($this, 'getTotalPrice'));
}
public function getTotalPrice(Items $items)
{
$total = 0;
foreach($items as $item){
$total += $item->getPrice();
}
return $total;
}
public function getName()
{
return 'app_extension';
}
}
Services:
services:
app.twig_extension:
class: Mp\ShopBundle\twig\AppExtension
public: false
tags:
- { name: twig.extension }
Now i want to count the sum of products with my extension like this:
{% for item in product %}
<td> ${{getTotalPrice(item)}}.00</td>
{% endfor %}
But i get this error:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Argument 1 passed to Mp\ShopBundle\twig\AppExtension::getTotalPrice() must be an instance of Mp\ShopBundle\twig\Items, instance of Mp\ShopBundle\Entity\Product given, called in C:\wamp\www\Digidis\tree\app\cache\dev\twig\b4\5d\b2cbf04f86aeef591812f9721d41a678d3fc5dbbd3aae638883d71c26af0.php on line 175 and defined") in MpShopBundle:Frontend:product_summary.html.twig at line 92.
Product:
<?php
namespace Mp\ShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Sonata\ClassificationBundle\Model\TagInterface;
use Sonata\ClassificationBundle\Model\Tag;
/**
* Product
*
* #ORM\Table(name="product", indexes={#ORM\Index(name="product_type_id", columns={"product_type_id"})})
* #ORM\Entity
*/
class Product
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="model", type="string", length=255, nullable=true)
*/
private $model;
/**
* #var \Mp\ShopBundle\Entity\ProductType
*
* #ORM\ManyToOne(targetEntity="Mp\ShopBundle\Entity\ProductType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="product_type_id", referencedColumnName="id")
* })
*/
private $productType;
/**
* #var \Mp\ShopBundle\Entity\ProductLanguageData
*
* #ORM\OneToMany(targetEntity="ProductLanguageData", mappedBy="product", cascade={"persist"}, orphanRemoval=true)
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id", referencedColumnName="product_id")
* })
*/
private $translations;
/**
* #var string
*
* #ORM\Column(name="admin_title", type="string", length=255, nullable=true)
*/
private $admin_title;
protected $tags;
/**
* #var \Application\Sonata\ClassificationBundle\Entity\Category
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\ClassificationBundle\Entity\Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \Application\Sonata\ClassificationBundle\Entity\Category
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\ClassificationBundle\Entity\Category")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="subcategory_id", referencedColumnName="id")
* })
*/
private $subcategory;
/**
* #var \Application\Sonata\ClassificationBundle\Entity\Collection
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\ClassificationBundle\Entity\Collection")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="manufacturer_id", referencedColumnName="id")
* })
*/
private $manufacturer;
/**
* #var boolean
*
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updated_at;
/**
* #ORM\Column(name="pc", type="decimal", precision=10, scale=2, nullable=true)
*/
private $pc;
/**
* #ORM\Column(name="value", type="decimal", precision=10, scale=2, nullable=true)
*/
private $value;
/**
* #ORM\Column(name="discount", type="decimal", precision=10, scale=2, nullable=true)
*/
private $discount;
/**
* #ORM\Column(name="base", type="decimal", precision=10, scale=2, nullable=true)
*/
private $base;
/**
* #ORM\Column(name="price", type="decimal", precision=10, scale=2, nullable=true)
*/
private $price;
/**
* #ORM\Column(name="stock", type="integer", nullable=true)
*/
private $stock;
/**
* #ORM\Column(name="map", type="string", length=255, nullable=true)
*/
private $map;
/**
* #ORM\Column(name="feature1", type="string", length=255, nullable=true)
*/
private $feature1;
/**
* #ORM\Column(name="feature2", type="string", length=255, nullable=true)
*/
private $feature2;
/**
* #ORM\Column(name="feature3", type="string", length=255, nullable=true)
*/
private $feature3;
/**
* #ORM\Column(name="feature4", type="string", length=255, nullable=true)
*/
private $feature4;
/**
* #ORM\Column(name="feature5", type="string", length=255, nullable=true)
*/
private $feature5;
/**
* #ORM\Column(name="feature6", type="string", length=255, nullable=true)
*/
private $feature6;
/**
* #ORM\Column(name="feature7", type="string", length=255, nullable=true)
*/
private $feature7;
/**
* #ORM\Column(name="feature8", type="string", length=255, nullable=true)
*/
private $feature8;
/**
* #var boolean
*
* #ORM\Column(name="published", type="boolean", nullable=true)
*/
private $published;
/**
* #ORM\Column(name="url_marketing", type="string", length=255, nullable=true)
*/
private $url_marketing;
/**
* #ORM\Column(name="cesion_tienda", type="string", length=255, nullable=true)
*/
private $cesion_tienda;
/**
* #ORM\Column(name="google", type="string", length=255, nullable=true)
*/
private $google;
/**
* #ORM\Column(name="provider_reference", type="string", length=255, nullable=true)
*/
private $provider_reference;
private $gallery;
/**
* #ORM\Column(name="vat", type="string", length=255, nullable=true)
*/
private $vat;
private $provider;
/**
* #var string
*
* #ORM\Column(name="video1", type="text", length=65535, nullable=true)
*/
private $video1;
/**
* #var string
*
* #ORM\Column(name="video2", type="text", length=65535, nullable=true)
*/
private $video2;
/**
* #var string
*
* #ORM\Column(name="friendly_url", type="string", length=255, nullable=true)
*/
private $friendly_url;
/**
* #var string
*
* #ORM\Column(name="shop_assignment", type="text", length=65535, nullable=true)
*/
private $shop_assignment;
/**
* #var string
*
* #ORM\Column(name="custom_product_type", type="string", length=255, nullable=true)
*/
private $custom_product_type;
/**
* Set model
*
* #param string $model
* #return Product
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* Get model
*
* #return string
*/
public function getModel()
{
return $this->model;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set productType
*
* #param \Mp\ShopBundle\Entity\ProductType $productType
* #return Product
*/
public function setProductType(\Mp\ShopBundle\Entity\ProductType $productType = null)
{
$this->productType = $productType;
return $this;
}
/**
* Get productType
*
* #return \Mp\ShopBundle\Entity\ProductType
*/
public function getProductType()
{
return $this->productType;
}
/**
* Get translations
*
* #return \Mp\ShopBundle\Entity\ProductLanguageData
*/
public function getTranslations()
{
return $this->translations;
}
/**
* Set translations
*
* #param \Doctrine\ORM\PersistentCollection $translations
* #return Product
*/
public function setTranslations(\Doctrine\ORM\PersistentCollection $translations)
{
$this->translations = new ArrayCollection();
foreach ($translations as $s) {
$this->addTranslation($s);
}
return $this;
}
/**
* Add translation
*
* #param \Mp\ShopBundle\Entity\ProductLanguageData $translation
*/
public function addTranslation(\Mp\ShopBundle\Entity\ProductLanguageData $translation)
{
$translation->setProduct($this);
$this->translations[] = $translation;
}
/**
* Remove translation
*
* #param \Mp\ShopBundle\Entity\ProductLanguageData $translation
*/
public function removeTranslation(\Mp\ShopBundle\Entity\ProductLanguageData $translation)
{
foreach ($this->translations as $k => $s) {
if ($s->getId() == $translation->getId()) {
unset($this->translations[$k]);
}
}
}
/**
* Get string value
*
* #return string
*/
public function __toString()
{
return ($this->admin_title == "") ? "Product" : $this->admin_title;
}
/**
* Constructor
*/
public function __construct()
{
//$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new ArrayCollection();
$this->status = false;
}
/**
* Set admin_title
*
* #param string $adminTitle
* #return Product
*/
public function setAdminTitle($adminTitle)
{
$this->admin_title = $adminTitle;
return $this;
}
/**
* Get admin_title
*
* #return string
*/
public function getAdminTitle()
{
return $this->admin_title;
}
/**
* Add tags
*
* #param \Sonata\ClassificationBundle\Model\TagInterface $tags
*/
public function addTags(TagInterface $tags)
{
$this->tags[] = $tags;
}
/**
* Get tags
*
* #return array $tags
*/
public function getTags()
{
return $this->tags;
}
/**
* #param $tags
*
* #return mixed
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* Set category
*
* #param \Application\Sonata\ClassificationBundle\Entity\Category $category
* #return Product
*/
public function setCategory(\Application\Sonata\ClassificationBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Application\Sonata\ClassificationBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Add tags
*
* #param \Application\Sonata\ClassificationBundle\Entity\Tag $tags
* #return Product
*/
public function addTag(\Application\Sonata\ClassificationBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Application\Sonata\ClassificationBundle\Entity\Tag $tags
*/
public function removeTag(\Application\Sonata\ClassificationBundle\Entity\Tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Set subcategory
*
* #param \Application\Sonata\ClassificationBundle\Entity\Category $subcategory
* #return Product
*/
public function setSubcategory(\Application\Sonata\ClassificationBundle\Entity\Category $subcategory = null)
{
$this->subcategory = $subcategory;
return $this;
}
/**
* Get subcategory
*
* #return \Application\Sonata\ClassificationBundle\Entity\Category
*/
public function getSubcategory()
{
return $this->subcategory;
}
/**
* Set manufacturer
*
* #param \Application\Sonata\ClassificationBundle\Entity\Collection $manufacturer
* #return Product
*/
public function setManufacturer(\Application\Sonata\ClassificationBundle\Entity\Collection $manufacturer = null)
{
$this->manufacturer = $manufacturer;
return $this;
}
/**
* Get manufacturer
*
* #return \Application\Sonata\ClassificationBundle\Entity\Collection
*/
public function getManufacturer()
{
return $this->manufacturer;
}
/**
* Set status
*
* #param boolean $status
* #return Product
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Product
*/
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 Product
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set pc
*
* #param string $pc
* #return Product
*/
public function setPc($pc)
{
$this->pc = $pc;
return $this;
}
/**
* Get pc
*
* #return string
*/
public function getPc()
{
return $this->pc;
}
/**
* Set value
*
* #param string $value
* #return Product
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set discount
*
* #param string $discount
* #return Product
*/
public function setDiscount($discount)
{
$this->discount = $discount;
return $this;
}
/**
* Get discount
*
* #return string
*/
public function getDiscount()
{
return $this->discount;
}
/**
* Set base
*
* #param string $base
* #return Product
*/
public function setBase($base)
{
$this->base = $base;
return $this;
}
/**
* Get base
*
* #return string
*/
public function getBase()
{
return $this->base;
}
/**
* Set price
*
* #param string $price
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set stock
*
* #param string $stock
* #return Product
*/
public function setStock($stock)
{
$this->stock = $stock;
return $this;
}
/**
* Get stock
*
* #return string
*/
public function getStock()
{
return $this->stock;
}
/**
* Set map
*
* #param string $map
* #return Product
*/
public function setMap($map)
{
$this->map = $map;
return $this;
}
/**
* Get map
*
* #return string
*/
public function getMap()
{
return $this->map;
}
/**
* Set feature1
*
* #param string $feature1
* #return Product
*/
public function setFeature1($feature1)
{
$this->feature1 = $feature1;
return $this;
}
/**
* Get feature1
*
* #return string
*/
public function getFeature1()
{
return $this->feature1;
}
/**
* Set feature2
*
* #param string $feature2
* #return Product
*/
public function setFeature2($feature2)
{
$this->feature2 = $feature2;
return $this;
}
/**
* Get feature2
*
* #return string
*/
public function getFeature2()
{
return $this->feature2;
}
/**
* Set feature3
*
* #param string $feature3
* #return Product
*/
public function setFeature3($feature3)
{
$this->feature3 = $feature3;
return $this;
}
/**
* Get feature3
*
* #return string
*/
public function getFeature3()
{
return $this->feature3;
}
/**
* Set feature4
*
* #param string $feature4
* #return Product
*/
public function setFeature4($feature4)
{
$this->feature4 = $feature4;
return $this;
}
/**
* Get feature4
*
* #return string
*/
public function getFeature4()
{
return $this->feature4;
}
/**
* Set feature5
*
* #param string $feature5
* #return Product
*/
public function setFeature5($feature5)
{
$this->feature5 = $feature5;
return $this;
}
/**
* Get feature5
*
* #return string
*/
public function getFeature5()
{
return $this->feature5;
}
/**
* Set feature6
*
* #param string $feature6
* #return Product
*/
public function setFeature6($feature6)
{
$this->feature6 = $feature6;
return $this;
}
/**
* Get feature6
*
* #return string
*/
public function getFeature6()
{
return $this->feature6;
}
/**
* Set feature7
*
* #param string $feature7
* #return Product
*/
public function setFeature7($feature7)
{
$this->feature7 = $feature7;
return $this;
}
/**
* Get feature7
*
* #return string
*/
public function getFeature7()
{
return $this->feature7;
}
/**
* Set feature8
*
* #param string $feature8
* #return Product
*/
public function setFeature8($feature8)
{
$this->feature8 = $feature8;
return $this;
}
/**
* Get feature8
*
* #return string
*/
public function getFeature8()
{
return $this->feature8;
}
/**
* Set published
*
* #param boolean $published
* #return Product
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* Set url_marketing
*
* #param string $urlMarketing
* #return Product
*/
public function setUrlMarketing($urlMarketing)
{
$this->url_marketing = $urlMarketing;
return $this;
}
/**
* Get url_marketing
*
* #return string
*/
public function getUrlMarketing()
{
return $this->url_marketing;
}
/**
* Set cesion_tienda
*
* #param string $cesionTienda
* #return Product
*/
public function setCesionTienda($cesionTienda)
{
$this->cesion_tienda = $cesionTienda;
return $this;
}
/**
* Get cesion_tienda
*
* #return string
*/
public function getCesionTienda()
{
return $this->cesion_tienda;
}
/**
* Set google
*
* #param string $google
* #return Product
*/
public function setGoogle($google)
{
$this->google = $google;
return $this;
}
/**
* Get google
*
* #return string
*/
public function getGoogle()
{
return $this->google;
}
/**
* Set provider_reference
*
* #param string $providerReference
* #return Product
*/
public function setProviderReference($providerReference)
{
$this->provider_reference = $providerReference;
return $this;
}
/**
* Get provider_reference
*
* #return string
*/
public function getProviderReference()
{
return $this->provider_reference;
}
/**
* Set gallery
*
* #param \Application\Sonata\MediaBundle\Entity\Gallery $gallery
* #return Product
*/
public function setGallery(\Application\Sonata\MediaBundle\Entity\Gallery $gallery = null)
{
$this->gallery = $gallery;
return $this;
}
/**
* Get gallery
*
* #return \Application\Sonata\MediaBundle\Entity\Gallery
*/
public function getGallery()
{
return $this->gallery;
}
/**
* Set vat
*
* #param string $vat
* #return Product
*/
public function setVat($vat)
{
$this->vat = $vat;
return $this;
}
/**
* Get vat
*
* #return string
*/
public function getVat()
{
return $this->vat;
}
/**
* Set provider
*
* #param \Application\Sonata\UserBundle\Entity\User $provider
* #return Product
*/
public function setProvider(\Application\Sonata\UserBundle\Entity\User $provider = null)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return \Application\Sonata\UserBundle\Entity\User
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set video1
*
* #param string $video1
* #return Product
*/
public function setVideo1($video1)
{
$this->video1 = $video1;
return $this;
}
/**
* Get custom_product_type
*
* #return string
*/
public function getCustomProductType()
{
return $this->custom_product_type;
}
}
So for some reason it is passing the wrong class? How can this be fixed?
Yes, you are passing the wrong class in your twig template.
In this part of code:
{% for item in product %}
<td>${{getTotalPrice(item)}}.00</td>
{% endfor %}
You are passing the item parameter which is the instance of Product class.
You should rewrite your Twig extension to accept Product instanses:
public function getTotalPrice($items)
{
$total = 0;
foreach($items as $item){
$total += $item->getPrice();
}
return $total;
}
And then pass the whole array, not only one Product:
<td>${{getTotalPrice(product)}}.00</td>
Hope this helps!
If you want pass a reference of you Product object (entity), you have to inform it to your method:
use Mp\ShopBundle\Entity\Product; - src/AppBundle/Twig/AppExtension.php
And then change your Items to Product object:
...
public function getTotalPrice(Product $items) {
....

Symfony2 Error: Attempted to call method on class "Doctrine\Common\Collections\ArrayCollection"

I have a problem with my Symfony project. I ask question on Stack Overflow because everything seems good for me but it's apparently not...
In my project I have a OneToOne bidirectional Doctrine relation between two table named "Visiteur" and "Coordonnees".
My problem appears when I submit my visiteur form. To be clear this form persist some data in "visiteur" table and it persist some data in "coordonnees" table ("imbricated form" translation from French to English)
Then I have the error below :
Attempted to call method "setVisiteur" on class
"Doctrine\Common\Collections\ArrayCollection".
There is my visiteurHandler.php who persist handle my data below.
The error appears in line 54:
$coordonnees->setVisiteur($visiteur);
The line below help me to be sure of my data type :
var_dump(gettype($coordonnees));
I obtain : string(6) "object" which is normal.
namespace Was\RHBundle\Form;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Was\RHBundle\Entity\Visiteur;
use Was\RHBundle\Entity\Coordonnees;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
class VisiteurHandler
{
protected $form;
protected $request;
protected $em;
public function __construct(Form $form, Request $request, EntityManager $em)
{
$this->form = $form;
$this->request = $request;
$this->em = $em;
}
public function process()
{
if ($this->request->getMethod() == 'POST') {
$this->form->bind($this->request);
if ($this->form->isValid() ) {
// echo '<pre>';
// print_r($this->request);
// echo '</pre>';
// die();
$this->onSuccess($this->form->getData());
return true;
}
}
return false;
}
public function onSuccess(Visiteur $visiteur)
{
$coordonnees=$visiteur->getCoordonnees();
$adresse=$visiteur->getAdresse();
var_dump(gettype($coordonnees));
$coordonnees->setVisiteur($visiteur);
$adresse->setVisiteur($visiteur);
$this->em->persist($coordonnees);
$this->em->persist($adresse);
$visiteur->setCoordonnees($coordonnees);
$visiteur->setAdresse($adresse);
$this->em->persist($visiteur);
$this->em->flush();
}
}
This is my entity visiteur which is my main entity :
<?php
namespace Was\RHBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContext;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Was\RHBundle\Entity\Visiteur
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Was\RHBundle\Entity\VisiteurRepository")
*
*/
class Visiteur
{
public function __toString()
{
return ucwords($this->prenom . " " . $this->nom);
}
public function __construct()
{
$this->createdAt = new \DateTime();
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->coordonnees = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var datetime $createdAt
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string $prenom
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var date $dateDebut
*
* #ORM\Column(name="dateDebut", type="date")
*/
private $dateDebut;
/**
* #var date $dateFin
*
* #ORM\Column(name="dateFin", type="date")
*/
private $dateFin;
/**
* #var string $service
*
* #ORM\Column(name="service", type="string", length=255)
*/
private $service;
/**
* #var string $fonction
*
* #ORM\Column(name="fonction", type="string", length=255)
*/
private $fonction;
/**
* #var text $remarqueSecurite
*
* #ORM\Column(name="remarqueSecurite", type="text", nullable=true)
*/
private $remarqueSecurite;
/**
* #ORM\OneToMany(targetEntity="Vehicule", mappedBy="visiteur", cascade={"remove"})
*/
private $vehicules;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Coordonnees", mappedBy="visiteur", cascade={"remove"})
*/
private $coordonnees;
/**
* #ORM\OneToOne(targetEntity="Adresse", mappedBy="visiteur", cascade={"remove"})
*/
private $adresse;
/**
* #ORM\ManyToOne(targetEntity="Agent")
* #ORM\JoinColumn(name="agent_id", referencedColumnName="id", nullable=true)
*/
private $hote;
public function isEnCours()
{
$maintenant = new \DateTime();
if ($maintenant > $this->dateDebut && $maintenant <= $this->dateFin || $this->dateFin == null) return true;
return false;
}
public function isAncien()
{
$maintenant = new \DateTime();
if ($maintenant > $this->dateDebut && $maintenant > $this->dateFin) return true;
return false;
}
public function isFutur()
{
$maintenant = new \DateTime();
if ($maintenant < $this->dateDebut && $maintenant <= $this->dateFin || $this->dateFin == null) return true;
return false;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set dateDebut
*
* #param date $dateDebut
*/
public function setDateDebut($dateDebut)
{
$this->dateDebut = $dateDebut;
}
/**
* Get dateDebut
*
* #return date
*/
public function getDateDebut()
{
return $this->dateDebut;
}
/**
* Set dateFin
*
* #param date $dateFin
*/
public function setDateFin($dateFin)
{
$this->dateFin = $dateFin;
}
/**
* Get dateFin
*
* #return date
*/
public function getDateFin()
{
return $this->dateFin;
}
/**
* Set service
*
* #param string $service
*/
public function setService($service)
{
$this->service = $service;
}
/**
* Get service
*
* #return string
*/
public function getService()
{
return $this->service;
}
/**
* Set remarqueSecurite
*
* #param text $remarqueSecurite
*/
public function setRemarqueSecurite($remarqueSecurite)
{
$this->remarqueSecurite = $remarqueSecurite;
}
/**
* Get remarqueSecurite
*
* #return text
*/
public function getRemarqueSecurite()
{
return $this->remarqueSecurite;
}
/**
* Add vehicules
*
* #param Was\RHBundle\Entity\Vehicule $vehicules
*/
public function addVehicule(\Was\RHBundle\Entity\Vehicule $vehicules)
{
$this->vehicules[] = $vehicules;
}
/**
* Get vehicules
*
* #return Doctrine\Common\Collections\Collection
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Set coordonnees
*
* #param Was\RHBundle\Entity\Coordonnees $coordonnees
*/
public function setCoordonnees(Coordonnees $coordonnees)
{
$this->coordonnees[] = $coordonnees;
//$coordonnees->setVisiteur($this);
//return $this;
}
/**
* Get coordonnees
*
* #return Was\RHBundle\Entity\Coordonnees
*/
public function getCoordonnees()
{
return $this->coordonnees;
}
/**
* Set adresse
*
* #param Was\RHBundle\Entity\Adresse $adresse
*/
public function setAdresse(\Was\RHBundle\Entity\Adresse $adresse)
{
$this->adresse = $adresse;
}
/**
* Get adresse
*
* #return Was\RHBundle\Entity\Adresse
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set createdAt
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* Get createdAt
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set fonction
*
* #param string $fonction
*/
public function setFonction($fonction)
{
$this->fonction = $fonction;
}
/**
* Get fonction
*
* #return string
*/
public function getFonction()
{
return $this->fonction;
}
/**
* Set hote
*
* #param Was\RHBundle\Entity\Agent $hote
*/
public function setHote(\Was\RHBundle\Entity\Agent $hote)
{
$this->hote = $hote;
}
/**
* Get hote
*
* #return Was\RHBundle\Entity\Agent
*/
public function getHote()
{
return $this->hote;
}
/**
* Remove vehicules
*
* #param Was\RHBundle\Entity\Vehicule $vehicules
*/
public function removeVehicule(\Was\RHBundle\Entity\Vehicule $vehicules)
{
$this->vehicules->removeElement($vehicules);
}
}
This my coordonnees Entity :
namespace Was\RHBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Was\UserBundle\Entity\User as User;
/**
* Was\RHBundle\Entity\Coordonnees
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Was\RHBundle\Entity\CoordonneesRepository")
* #UniqueEntity(fields="emailPro", message="Cet email professionnel est déjà pris.")
*/
class Coordonnees
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $telPro
*
* #ORM\Column(name="telPro", type="string", length=255, nullable=true)
*/
private $telPro;
/**
* #var string $telFax
*
* #ORM\Column(name="telFax", type="string", length=255, nullable=true)
*/
private $telFax;
/**
* #var string $telPortable
*
* #ORM\Column(name="telPortable", type="string", length=255, nullable=true)
*/
private $telPortable;
/**
* #var string $telDomicile
*
* #ORM\Column(name="telDomicile", type="string", length=255, nullable=true)
*/
private $telDomicile;
/**
* #var string $telAutre
*
* #ORM\Column(name="telAutre", type="string", length=255, nullable=true)
*/
private $telAutre;
/**
* #var string $telUrgence
*
* #ORM\Column(name="telUrgence", type="string", length=255, nullable=true)
*/
private $telUrgence;
/**
* #ORM\Column(name="contactUrgence", type="text", nullable=true)
*/
private $contactUrgence;
/**
* #ORM\Column(name="contactUrgenceUS", type="text", nullable=true)
*/
private $contactUrgenceUS;
/**
* #var string $numeroBadge
*
* #ORM\Column(name="numeroBadge", type="string", length=255, nullable=true)
*/
private $numeroBadge;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Email(message="Email personnel invalide.")
*/
private $emailPerso;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Email(message="Email professionnel invalide.")
*/
private $emailPro;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Agent", inversedBy="coordonnees")
* #ORM\JoinColumn( name="agent_id", referencedColumnName="id")
*/
private $agent;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Visiteur", inversedBy="coordonnees")
* #ORM\JoinColumn(name="visiteur_id", referencedColumnName="id")
*/
private $visiteur;
/**
* #var datetime $updatedAt
*
* #ORM\Column(name="updatedAt", type="datetime", nullable=true)
*/
private $updatedAt;
/**
* #ORM\ManyToOne(targetEntity="\Was\UserBundle\Entity\User")
* #ORM\JoinColumn(name="updated_by_id", referencedColumnName="id", nullable=true)
*/
private $updatedBy;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set telPro
*
* #param string $telPro
*/
public function setTelPro($telPro)
{
$this->telPro = $telPro;
}
/**
* Get telPro
*
* #return string
*/
public function getTelPro()
{
return $this->telPro;
}
/**
* Set telFax
*
* #param string $telFax
*/
public function setTelFax($telFax)
{
$this->telFax = $telFax;
}
/**
* Get telFax
*
* #return string
*/
public function getTelFax()
{
return $this->telFax;
}
/**
* Set telPortable
*
* #param string $telPortable
*/
public function setTelPortable($telPortable)
{
$this->telPortable = $telPortable;
}
/**
* Get telPortable
*
* #return string
*/
public function getTelPortable()
{
return $this->telPortable;
}
/**
* Set telDomicile
*
* #param string $telDomicile
*/
public function setTelDomicile($telDomicile)
{
$this->telDomicile = $telDomicile;
}
/**
* Get telDomicile
*
* #return string
*/
public function getTelDomicile()
{
return $this->telDomicile;
}
/**
* Set telAutre
*
* #param string $telAutre
*/
public function setTelAutre($telAutre)
{
$this->telAutre = $telAutre;
}
/**
* Get telAutre
*
* #return string
*/
public function getTelAutre()
{
return $this->telAutre;
}
/**
* Set telUrgence
*
* #param string $telUrgence
*/
public function setTelUrgence($telUrgence)
{
$this->telUrgence = $telUrgence;
}
/**
* Get telUrgence
*
* #return string
*/
public function getTelUrgence()
{
return $this->telUrgence;
}
/**
* Set agent
*
* #param Was\RHBundle\Entity\Agent $agent
*/
public function setAgent(\Was\RHBundle\Entity\Agent $agent)
{
$this->agent = $agent;
}
/**
* Get agent
*
* #return Was\RHBundle\Entity\Agent
*/
public function getAgent()
{
return $this->agent;
}
/**
* Set emailPerso
*
* #param string $emailPerso
*/
public function setEmailPerso($emailPerso)
{
$this->emailPerso = $emailPerso;
}
/**
* Get emailPerso
*
* #return string
*/
public function getEmailPerso()
{
return $this->emailPerso;
}
/**
* Set emailPro
*
* #param string $emailPro
*/
public function setEmailPro($emailPro)
{
$this->emailPro = $emailPro;
}
/**
* Get emailPro
*
* #return string
*/
public function getEmailPro()
{
return $this->emailPro;
}
/**
* Set visiteur
*
* #param Was\RHBundle\Entity\Visiteur $visiteur
*/
public function setVisiteur(\Was\RHBundle\Entity\Visiteur $visiteur)
{
$this->visiteur = $visiteur;
}
/**
* Get visiteur
*
* #return Was\RHBundle\Entity\Visiteur
*/
public function getVisiteur()
{
return $this->visiteur;
}
/**
* Set updatedAt
*
* #param datetime $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* Get updatedAt
*
* #return datetime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set updatedBy
*
* #param Was\UserBundle\Entity\User $updatedBy
*/
public function setUpdatedBy($updatedBy)
{
$this->updatedBy = $updatedBy;
}
/**
* Get updatedBy
*
* #return Was\UserBundle\Entity\User
*/
public function getUpdatedBy()
{
return $this->updatedBy;
}
/**
* Set numeroBadge
*
* #param string $numeroBadge
*/
public function setNumeroBadge($numeroBadge)
{
$this->numeroBadge = $numeroBadge;
}
/**
* Get numeroBadge
*
* #return string
*/
public function getNumeroBadge()
{
return $this->numeroBadge;
}
/**
* Set contactUrgence
*
* #param text $contactUrgence
*/
public function setContactUrgence($contactUrgence)
{
$this->contactUrgence = $contactUrgence;
}
/**
* Get contactUrgence
*
* #return text
*/
public function getContactUrgence()
{
return $this->contactUrgence;
}
/**
* Set contactUrgenceUS
*
* #param text $contactUrgenceUS
*/
public function setContactUrgenceUS($contactUrgenceUS)
{
$this->contactUrgenceUS = $contactUrgenceUS;
}
/**
* Get contactUrgenceUS
*
* #return text
*/
public function getContactUrgenceUS()
{
return $this->contactUrgenceUS;
}
}
You say (and define it with annotations) that it's a OneToOne relation.
But look in to Visiteur entity class.
You set cordonnees to be an ArrayCollection instead of single Coordonness entity object in constructor.
public function __construct()
{
$this->createdAt = new \DateTime();
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->coordonnees = new \Doctrine\Common\Collections\ArrayCollection(); // <-- here
}
And futher in setter you use it as an array too:
/**
* Set coordonnees
*
* #param Was\RHBundle\Entity\Coordonnees $coordonnees
*/
public function setCoordonnees(Coordonnees $coordonnees)
{
$this->coordonnees[] = $coordonnees;
//$coordonnees->setVisiteur($this);
//return $this;
}
So the getter returns an array (ArrayCollection object actually) of entities.
Let's look at the problematic code:
public function onSuccess(Visiteur $visiteur)
{
$coordonnees=$visiteur->getCoordonnees(); //this returns ArrayCollection of Coordnnees entity objects
$adresse=$visiteur->getAdresse();
var_dump(gettype($coordonnees)); // yes, it says "object" because it's instance of ArrayCollection class
$coordonnees->setVisiteur($visiteur); //Now you should know, why it won't work. It's not an entity object, but ArrayCollection of entity objects.
//(...)
}
I think that $coordonneess shoudn't be an ArrayCollection since it's OneToOne relation.

Symfony 2 computer hungs when I make any request

Excuse me for my English.
I have 3 classes: User, Category and Service.
When I do even a simple query to the database for Service, for example findAll(), my computer hangs... At the same time, the query for Category and User are good.
Thank you for your help!
User.php
namespace General\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your type.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max="255",
* minMessage="The type is too short.",
* maxMessage="The type is too long.",
* groups={"Registration", "Profile"}
* )
*/
protected $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
}
Category.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Category
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\OneToMany(targetEntity="\General\AnnuaireBundle\Entity\Service", mappedBy="categories")
*/
private $services;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
$this->services = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* 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 statut
*
* #param boolean $statut
* #return Category
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* #ORM\PrePersist()
*/
public function setCreatedAt($createdAt = null) {
$this->createdAt = null === $createdAt ? new \DateTime() : $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add services
*
* #param \General\AnnuaireBundle\Entity\Service $services
* #return Category
*/
public function addService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services[] = $services;
return $this;
}
/**
* Remove services
*
* #param \General\AnnuaireBundle\Entity\Service $services
*/
public function removeService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services->removeElement($services);
}
/**
* Get services
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServices()
{
return $this->services;
}
}
Service.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\ServiceRepository")
*/
class Service
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToOne(targetEntity="\General\AnnuaireBundle\Entity\Category", inversedBy="services")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $categories;
/**
* #ORM\ManyToOne(targetEntity="\General\UserBundle\Entity\User")
*/
private $users;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Service
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Service
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Service
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Service
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set categories
*
* #param \General\AnnuaireBundle\Entity\Category $categories
* #return Service
*/
public function setCategories(\General\AnnuaireBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return \General\AnnuaireBundle\Entity\Category
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set users
*
* #param \General\UserBundle\Entity\User $users
* #return Service
*/
public function setUsers(\General\UserBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* #return \General\UserBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
}
Controller.php
public function showServicesAction()
{
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services,
)
);
}
If I modified my function as:
$user = $this->container->get('security.context')->getToken()->getUser();
$user_id = $user->getId();
// var_dump($user_id); ALL IS RIGHT
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
// var_dump($user_id); ALL IS RIGHT
// IF: var_dump($services[0]); COMPUTER HUNGS
// IF: echo count($services); RESPONSE RIGHT
// IF:
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services, ));
// SCREEN WHITE
If you print object in browser it get hanged because symphony object contains lots of info. suppose if you have relation with other tables it will have current tables info as well as other related tables info (Schema, Data, Relationship etc.) as well so it might 99% chance to hanged the browser. Better to print "echo count($services)" to check object exists or not.
Try Debug::dump($service) or any variable - you will be able to see the objects (without the proxy)

Categories