Symfony 3.3 and doctrine 2 - doctrine-orm

I have two entities Article and Image related by a ManytoMany relations using a third entity called ArticlesHaveImages.
I don't use classical ManytoMany relation of Doctrine because I have a third field in ArticlesHaveImages called sequence.
class Article
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
...
/**
* One Article has Many articleHaveImage.
* #ORM\OneToMany(targetEntity="ArticlesHaveImages", mappedBy="article")
*/
private $images;
class Image
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
...
/**
* One Image has Many articleHaveImage.
* #ORM\OneToMany(targetEntity="ArticlesHaveImages", mappedBy="image")
*/
private $articles;
public function __construct() {
$this->articles = new ArrayCollection();
}
class ArticlesHaveImages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Many ArticlesHaveImages have One Article.
* #ORM\ManyToOne(targetEntity="Article", inversedBy="images")
* #ORM\JoinColumn(name="article_id", referencedColumnName="id")
*/
private $article;
/**
* Many ArticlesHaveImages have One Image.
* #ORM\ManyToOne(targetEntity="Image", inversedBy="articles")
* #ORM\JoinColumn(name="image_id", referencedColumnName="id")
*/
private $image;
/**
* #var int
*
* #ORM\Column(name="sequence", type="integer")
*/
private $sequence;
How do I create a form out of this ?
I want a multiple select option which all images name.
I tried :
class ArticleType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$images = $options['images'];
$builder
->add('translations', CollectionType::class, array(
'entry_type' => ArticleTranslationType::class,
'entry_options' => array('label' => false)))
->add('images', ChoiceType::class, array(
"required" => false,
"choices" => $images,
'multiple' => true,
But I get :
Could not determine access type for property "images" in class
"AppBundle\Entity\Article".
BIG THANKS !

Related

Getting the values of one-to-many relationships in the parent entity?

So I have a Doctrine 2 ORM entity, Trust, with several one-to-many relationships. I can't work out how to populate the arrays for these.
class Trust implements \JsonSerializable {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="TrustPurpose", mappedBy="trust")
*/
private $purpose;
public function __construct() {
}
public function jsonSerialize() {
return [
'id' => $this->id,
'name' => $this->name,
[...]
'purpose' => $this->purpose,
[...]
];
}
}
In my controller, I might use something like the following.
return new JsonResponse($this->entityManager->find(Trust::class, 1));
And get the following output
{
"id" : 1,
"name" : "Some Trust",
"purpose" : {
}
}
I'm struggling to find documentation on how to edit entity Trust to automatically populate my purpose records?
TrustPurpose
class TrustPurpose implements \JsonSerializable {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $purpose;
/**
* #ORM\ManyToOne(targetEntity="Trust", inversedBy="purpose")
* #ORM\JoinColumn(name="trust_id", referencedColumnName="id")
*/
private $trust;
public function __construct() {
}
public function jsonSerialize() {
return [
'id' => $this->id,
'purpose' => $this->purpose,
'trust' => $this->trust,
];
}
}

Get access through another Entity in Doctrine2

I have the problem with Association in Doctrine2.
My Entity mapping is:
Brand:
/**
* #ORM\Entity
*/
class Brand
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Model", mappedBy="brand")
*/
protected $models;
/**
* #ORM\Column(type="boolean")
*/
protected $isPopular;
}
Model:
/**
* #ORM\Entity
*/
class Model
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\VehicleType", inversedBy="models")
* #ORM\JoinColumn(name="vehicle_type_id", referencedColumnName="id")
*/
protected $vehicleType;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Brand", inversedBy="models")
* #ORM\JoinColumn(name="brand_id", referencedColumnName="id")
*/
protected $brand;
}
VehicleType:
/**
* #ORM\Entity
*/
class VehicleType
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Model", mappedBy="vehicleType")
*/
protected $models;
}
How I can get in Entity VehicleType array of popular Brands (brand.isPopular = true)?
Мay be my mapping is wrong?
I can do like this
$vehicleTypes = $this->getEm()->getRepository('AppBundle:VehicleType')->findAll();
foreach ($vehicleTypes as $vehicleType) {
print ('<p>'.$vehicleType->getName().'</p>');
$brands = $this->getQb()
->select('brand')
->from('AppBundle:Brand', 'brand')
->join('brand.models', 'models')
->where('brand.isPopular = true')
->andWhere('models.vehicleType = :vehicleType')
->setParameter('vehicleType', $vehicleType)
->getQuery()
->getResult()
;
foreach ($brands as $brand) {
print('<p> - '.$brand->getNameEng().'</p>');
}
}
But I have n+1 querys to DB, where n size of VehicleType. Posible decrise DB querys?

A new entity was found through the relationship - error

I try to establish a simple association of two tables. But I always geht the following error:
A new entity was found through the relationship 'Shopware\CustomModels\JoeKaffeeAbo\Client#abos' that was not configured to cascade persist operations for entity: Shopware\CustomModels\JoeKaffeeAbo\Abo#00000000211b173900000000cf7658ac
Here are my Models:
<?php
namespace Shopware\CustomModels\JoeKaffeeAbo;
use Symfony\Component\Validator\Constraints as Assert,
Doctrine\Common\Collections\ArrayCollection,
Shopware\Components\Model\ModelEntity,
Doctrine\ORM\Mapping AS ORM;
/**
* #ORM\Entity
* #ORM\Table(name="joe_kaffee_abo_abos")
*/
class Abo extends ModelEntity
{
public function __construct() {
$client = new ArrayCollection();
}
/**
* Unique identifier
*
* #var integer
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Shopware\CustomModels\JoeKaffeeAbo\Client", inversedBy="abos", cascade={"persist", "remove"})
**/
protected $clients;
/**
* #var string
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
protected $name = '';
/**
* #var string
* #ORM\Column(name="desc", type="string", length=255, nullable=true)
*/
protected $desc = '';
/**
* #var string
* #ORM\Column(name="name_en", type="string", length=255, nullable=true)
*/
protected $name_en = '';
/**
* #var string
* #ORM\Column(name="desc_en", type="string", length=255, nullable=true)
*/
protected $desc_en = '';
//getter and setters...
}
?>
Client Model:
<?php
namespace Shopware\CustomModels\JoeKaffeeAbo;
use Symfony\Component\Validator\Constraints as Assert,
Doctrine\Common\Collections\ArrayCollection,
Shopware\Components\Model\ModelEntity,
Doctrine\ORM\Mapping AS ORM;
/**
* #ORM\Entity
* #ORM\Table(name="joe_kaffee_abo_client")
*/
class Client extends ModelEntity
{
public function __construct() {
$this->abos = new ArrayCollection();
}
/**
* Unique identifier
*
* #var integer
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Shopware\CustomModels\JoeKaffeeAbo\Abo", mappedBy="clients", cascade={"persist", "remove"})
**/
protected $abos = null;
public function addAbo($abo)
{
$abo->addClient($this);
$this->abos[] = $abo;
}
/**
* #var integer
* #ORM\Column(name="customerid", type="integer", nullable=true)
*/
protected $customerid;
/**
* #var integer
* #ORM\Column(name="customernumber", type="integer", nullable=true)
*/
protected $customernumber;
/**
* #var boolean
* #ORM\Column(name="is_active", type="boolean", nullable=true)
*/
protected $is_active;
//Getters and Setters
}
?>
The error occurs after I executed the following statements:
$client = new Client();
$client->setCustomerid(12);
$client->setCustomernumber(12);
$client->setIs_active(true);
Shopware()->Models()->persist($client);
$abo = new Abo();
$abo->setName("name");
$abo->setDesc("desc");
$abo->setName_en("name");
$abo->setDesc_en("desc");
$client->addAbo($abo);
//$abo->addClient($client);
//$client->addAbo($abo);
Shopware()->Models()->persist($client);
//Shopware()->Models()->persist($abo);
Shopware()->Models()->flush();
What this is telling you is that you need to save the Abo Entity before saving the client.
$abo = new Abo();
$abo->setName("name");
$abo->setDesc("desc");
$abo->setName_en("name");
$abo->setDesc_en("desc");
Shopware()->Models()->persist($abo); //Persist the Abo before assigning it to the client
$client->addAbo($abo);
//$abo->addClient($client);
//$client->addAbo($abo);
Shopware()->Models()->persist($client);
//Shopware()->Models()->persist($abo);
Shopware()->Models()->flush();

ZF2 doctrine OneToMany annotation form

I have following entities:
User
/**
* Users
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Users\Entity\Repository\UsersRepository")
* #Annotation\Name("user")
* #Annotation\Hydrator("Zend\Stdlib\Hydrator\ClassMethods")
*/
class User
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=false)
* #Annotation\Filter({"name":"StringTrim"})
* #Annotation\Validator({"name":"StringLength", "options":{"min":2, "max":100}})
* #Annotation\Attributes({"type":"text","class":"form-control"})
* #Annotation\Options({"label":"Full name:"})
*/
private $name;
/**
* #var User\Entity\UserItem
*
* #ORM\OneToMany(targetEntity="User\Entity\UserItem", mappedBy="user")
* #Annotation\Exclude()
*/
private $items;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Annotation\Exclude()
*/
private $id;
public function __construct()
{
$this->vessels = new ArrayCollection();
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function getId()
{
return $this->id;
}
public function getItems()
{
return $this->items
}
public function setItems($items)
{
$this->itemr = $items;
return $this;
}
Item
/**
* Items
* #ORM\Entity
* #ORM\Table(name="items")
* #ORM\Entity(repositoryClass="User\Entity\Repository\ItemsRepository")
* #Annotation\Name("item")
* #Annotation\Hydrator("Zend\Stdlib\Hydrator\ClassMethods")
*/
class Item
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=false)
* #Annotation\Filter({"name":"StringTrim"})
* #Annotation\Validator({"name":"StringLength", "options":{"min":2, "max":100}})
* #Annotation\Attributes({"type":"text","class":"form-control"})
* #Annotation\Options({"label":"Name:"})
*/
private $name;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Annotation\Exclude()
*/
private $id;
And finally entity keepeing relation between those two
UserItem
/**
* UserItem
*
* #ORM\Table(name="users_items")
* #ORM\Entity(repositoryClass="User\Entity\Repository\UserItemsRepository")
* #Annotation\Name("user_item")
* #Annotation\Hydrator("Zend\Stdlib\Hydrator\ClassMethods")
*/
class UserItem{
/**
* #var Users\Entity\User
*
* #ORM\ManyToOne(targetEntity="Users\Entity\User", inversedBy="items")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* #Annotation\Exclude()
*/
private $user;
/**
* #var User\Entity\Item
*
* #ORM\ManyToOne(targetEntity="User\Entity\Item", inversedBy="users")
* #ORM\JoinColumn(name="item_id", referencedColumnName="id")
* #Annotation\Type("DoctrineModule\Form\Element\ObjectSelect")
*/
private $item;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Annotation\Exclude()
*/
private $id;
With this entities i can create and edit User and Item. Form are generated from annotations.
My question is how can i generate form for assigning items to user. Preferably as select field(s) with multiple selection. And after submitting doctrine should save the relations.
I wrote this form to represent items to select:
class ItemsForm extends Form
{
public function __construct($entityManager, $name = null)
{
parent::__construct('items');
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'items',
'attributes' => array(
'id' => 'selectItems',
'multiple' => true,
'data-placeholder' => 'Items'
),
'options' => array(
'object_manager' => $entityManager,
'target_class' => 'User\Entity\Item',
'property' => 'name',
),
)
);
}
}
And now i do not know how to preselect items user has already assigned.
In select field in value you must have id from items. After submit you can do something like that
foreach($post['items'] as $itemId)
{
$userItem = new UserItem();
$userItem->user = $this->getEntityManager()->getReference('User', $userId);
$userItem->item = $this->getEntityManager()->getReference('Item', $itemId);
$this->getEntityManager()->save($userItem);
}

Updating Doctrine Collection

I'm working on a survey project and I got 3 Entities, survey(umfrage), surveyQuestion(umfrageFrage) and surveyAnswer(umfrageAntwort).
Here are the entities(removed all unnecessary fields):
namespace Umfrage\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* Umfrage
*
* #ORM\Table(name="umfrage")
* #ORM\Entity
*/
class Umfrage
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Fragen
*
* #ORM\OneToMany(targetEntity="Umfrage\Entity\UmfrageFrage", mappedBy="umfrage", cascade={"persist","remove"})
*/
private $fragen;
public function __construct() {
$this->fragen = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fragen
*
* #param \Umfrage\Entity\UmfrageFrage $fragen
*
* #return UmfrageFrage
*/
public function setFragen($fragen)
{
$this->fragen = $fragen;
return $this;
}
/** Get fragen
*
* #param \Umfrage\Entity\UmfrageFrage $fragen
*
* #return UmfrageFrage
*/
public function getFragen() {
return $this->fragen;
}
public function addFragen(Collection $fragen)
{
foreach ($fragen as $frage) {
$frage->setUmfrage($this);
$this->fragen->add($frage);
}
}
public function removeFragen(Collection $fragen)
{
foreach ($fragen as $frage) {
$frage->setUmfrage(null);
$this->fragen->removeElement($frage);
}
}
}
The Questions:
namespace Umfrage\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* UmfrageFrage
*
* #ORM\Table(name="umfrage_frage")
* #ORM\Entity
*/
class UmfrageFrage
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Umfrage\Entity\Umfrage
*
* #ORM\ManyToOne(targetEntity="Umfrage\Entity\Umfrage", inversedBy="fragen")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="umfrage_id", referencedColumnName="id")
* })
*/
private $umfrage;
/**
* #var Antworten
*
* #ORM\OneToMany(targetEntity="Umfrage\Entity\UmfrageAntwort", mappedBy="umfrageFrage", cascade={"all"})
*/
private $antworten;
public function __construct() {
$this->antworten = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set umfrage
*
* #param \Umfrage\Entity\Umfrage $umfrage
*
* #return UmfrageFrage
*/
public function setUmfrage(\Umfrage\Entity\Umfrage $umfrage = null)
{
$this->umfrage = $umfrage;
return $this;
}
/**
* Get umfrage
*
* #return \Umfrage\Entity\Umfrage
*/
public function getUmfrage()
{
return $this->umfrage;
}
/**
* Set antworten
*
* #param \Umfrage\Entity\UmfrageAntwort $antworten
*
* #return UmfrageAntwort
*/
public function setAntworten($antworten)
{
$this->antworten = $antworten;
return $this;
}
/** Get antworten
*
* #param \Umfrage\Entity\UmfrageAntwort $antworten
*
* #return UmfrageAntwort
*/
public function getAntworten() {
return $this->antworten;
}
public function addAntworten(Collection $antworten)
{
foreach ($antworten as $antwort) {
$antwort->setUmfrageFrage($this);
$this->antworten->add($antwort);
}
}
public function removeAntworten(Collection $antworten)
{
foreach ($antworten as $antwort) {
$this->antworten->removeElement($antwort);
}
}
}
The Answers:
namespace Umfrage\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* UmfrageAntwort
*
* #ORM\Table(name="umfrage_antwort")
* #ORM\Entity
*/
class UmfrageAntwort
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Umfrage\Entity\UmfrageFrage
*
* #ORM\ManyToOne(targetEntity="Umfrage\Entity\UmfrageFrage", inversedBy="antworten")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="umfrage_frage_id", referencedColumnName="id")
* })
*/
private $umfrageFrage;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set umfrageFrage
*
* #param \Umfrage\Entity\UmfrageFrage $umfrageFrage
*
* #return UmfrageFrage
*/
public function setUmfrageFrage($umfrageFrage)
{
$this->umfrageFrage = $umfrageFrage;
return $this;
}
/**
* Get umfrageFrage
*
* #return \Umfrage\Entity\UmfrageFrage
*/
public function getUmfrageFrage()
{
return $this->umfrageFrage;
}
}
The Controller action:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('umfrage', array('action'=>'add'));
}
$umfrage = $this->getEntityManager()->find('Umfrage\Entity\Umfrage', $id);
$form = new UmfrageForm($this->getEntityManager());
$form->setHydrator(new DoctrineEntity($this->getEntityManager(),'Umfrage\Entity\Umfrage'));
$form->bind($umfrage);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getEntityManager()->persist($umfrage);
$this->getEntityManager()->flush();
// Redirect to overview
return $this->redirect()->toRoute('umfrage');
}
}
$this->layout('layout/umfrage_backend');
return new ViewModel(array(
'id' => $id,
'form' => $form
));
}
And the view:
<?php
// module/Umfrage/view/umfrage/umfrage/edit.phtml:
use Doctrine\Common\Util\Debug;
$title = 'Umfrage bearbeiten';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'umfrage',
array(
'action' => 'edit',
'id' => $this->id,
)
));
echo $this->ztbForm($form);
?>
Adding a Survey works fine, Deleting also, the Survey and its related Questions/Answers are removed from the DB. Only the Update actions doesn't work as expected. Survey and Questions are updated, but for the Answers I receive an Insert, instead of an Update, which results in duplicate entries in the DB. What's wrong with the Mapping(Code)?
Thanks in advance for your help!