Doctrine inversedBy field contains PersistentCollection - mysql

I have relation between two tables through third with extra row (s) like in this question
/** #Entity
*/
class Illness {
/** #Id #GeneratedValue #Column(type="integer") */
private $illness_id;
/** #Column(type="string") */
private $name;
/** #OneToMany(targetEntity="Illness_Symptom_Association", mappedBy="Illness") */
private $symptAssoc;
public function __construct()
{
$this->symptAssoc = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setName($val)
{
$this->name = $val;
}
public function getName()
{
return $this->name;
}
public function getSymptAssoc()
{
return $this->symptAssoc;
}
}
Join table with third param s (something like priority)
/**
* #Entity
*/
class Illness_Symptom_Association {
protected $illness_id;
/**
* #Id()
* #ManyToOne(targetEntity="Illness", inversedBy="symptAssoc")
* #JoinColumn(name="illness_id", referencedColumnName="illness_id", nullable=false)
*/
protected $illness;
/**
* #Id()
* #ManyToOne(targetEntity="Symptom", inversedBy="symptAssoc")
* #JoinColumn(name="symptom_id", referencedColumnName="symptom_id")
* */
protected $symptom;
/** #Column(type="integer") */
protected $s;
public function setIllness(Illness $illness)
{
$this->illness = $illness;
}
/**
*
* #return Illness
*/
public function getIllness()
{
return $this->illness;
}
public function setSymptom(Symptom $sympt)
{
return $this->symptom = $sympt;
}
public function getSymptom()
{
return $this->symptom;
}
public function setS($s)
{
$this->s = $s;
}
public function getS()
{
return $this->s;
}
}
Last entity with symptoms:
/**
* #Entity
*/
class Symptom {
/** #Id #GeneratedValue #Column(type="integer") */
protected $symptom_id;
/** #Column(type="string", unique=true) */
protected $name;
/** #OneToMany(targetEntity="Illness_Symptom_Association", mappedBy="symptom") */
protected $symptAssoc;
public function setName($name)
{
$this->name = $name;
}
public function getName($name)
{
return $this->name;
}
}
But
$illness = $em->getRepository('Entity\Illness')->find($id);
$illness->getSymptAssoc();
return PersistentCollection oject.
How I can get list of symptoms with s param from join table?

A PersistentCollection is a Collection (of Symptom objects, in this case). It already is a list of symptoms.
You can iterate it (just like an array), access its elements (which are Symptom objects in this case), or convert it to an array:
$illness->getSymptAssoc()->toArray();

Related

"No identifier/primary key specified for Entity" Error on a view entity

Symfony 6
No identifier/primary key specified for Entity "App\Entity\ContactVw".
Every Entity must have an identifier/primary key.
I know how to fix that error when using a simple table.
But how can I fix that error when I am using a view. Views don't have primary keys. Where in the class definition do I have to tell doctrine what column to use as primary?
This is my class
<?php
namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
/**
* ContactVw
*
* #ORM\Table(name="contact_vw", indexes={#ORM\Index(name="city", columns={"city"}), #ORM\Index(name="customer", columns={"customer"}), #ORM\Index(name="name", columns={"name"}), #ORM\Index(name="country_sold_to", columns={"country_sold_to"})})
* #ORM\Entity
*/
class ContactVw
{
public function __construct(
#[Id, Column]
private string $contactId,
) {
}
/**
* #var string|null
*
* #ORM\Column(name="first", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $first = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="middle", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $middle = 'NULL';
/**
* #var string
*
* #ORM\Column(name="last", type="string", length=255, nullable=false)
*/
private $last;
/**
* #var string
*
* #ORM\Column(name="customer", type="decimal", precision=38, scale=0, nullable=false)
*/
private $customer;
/**
* #var string|null
*
* #ORM\Column(name="email", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $email = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="phone", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $phone = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="mobile", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $mobile = 'NULL';
/**
* #var bool
*
* #ORM\Column(name="skill_id", type="boolean", nullable=false)
*/
private $skillId;
/**
* #var string
*
* #ORM\Column(name="skill", type="string", length=255, nullable=false)
*/
private $skill;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=2, nullable=false)
*/
private $country;
/**
* #var string|null
*
* #ORM\Column(name="country_sold_to", type="string", length=41, nullable=true, options={"default"="NULL"})
*/
private $countrySoldTo = 'NULL';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=35, nullable=false)
*/
private $name;
/**
* #var string|null
*
* #ORM\Column(name="name_2", type="string", length=35, nullable=true, options={"default"="NULL"})
*/
private $name2 = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="postal_code", type="decimal", precision=38, scale=0, nullable=true, options={"default"="NULL"})
*/
private $postalCode = 'NULL';
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=35, nullable=false)
*/
private $city;
public function setContactId(int $contactId): self
{
$this->contactId = $contactId;
return $this;
}
public function getFirst(): ?string
{
return $this->first;
}
public function setFirst(?string $first): self
{
$this->first = $first;
return $this;
}
public function getMiddle(): ?string
{
return $this->middle;
}
public function setMiddle(?string $middle): self
{
$this->middle = $middle;
return $this;
}
public function getLast(): ?string
{
return $this->last;
}
public function setLast(string $last): self
{
$this->last = $last;
return $this;
}
public function getCustomer(): ?string
{
return $this->customer;
}
public function setCustomer(string $customer): self
{
$this->customer = $customer;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getMobile(): ?string
{
return $this->mobile;
}
public function setMobile(?string $mobile): self
{
$this->mobile = $mobile;
return $this;
}
public function isSkillId(): ?bool
{
return $this->skillId;
}
public function setSkillId(bool $skillId): self
{
$this->skillId = $skillId;
return $this;
}
public function getSkill(): ?string
{
return $this->skill;
}
public function setSkill(string $skill): self
{
$this->skill = $skill;
return $this;
}
public function getCountry(): ?string
{
return $this->country;
}
public function setCountry(string $country): self
{
$this->country = $country;
return $this;
}
public function getCountrySoldTo(): ?string
{
return $this->countrySoldTo;
}
public function setCountrySoldTo(?string $countrySoldTo): self
{
$this->countrySoldTo = $countrySoldTo;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getName2(): ?string
{
return $this->name2;
}
public function setName2(?string $name2): self
{
$this->name2 = $name2;
return $this;
}
public function getPostalCode(): ?string
{
return $this->postalCode;
}
public function setPostalCode(?string $postalCode): self
{
$this->postalCode = $postalCode;
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(string $city): self
{
$this->city = $city;
return $this;
}
}
You did not set an identifier on any attribute, which you can do using :
#[ORM\Id] // Php Attribute
/**
* #ORM\Id // Annotation
**/
enter code here
In your code :
#[Id, Column] // seems wrong
You are mixing annotation and Php Attribute to define how your entity work: dont do that.
Personnally, i recommend php attribute over annotation if you can use it.
https://symfony.com/blog/new-in-symfony-5-2-php-8-attributes

Deserializing an Object in Symfony

I retrieved the json response of a mailjet API in $ Data
class DefaultController extends FOSRestController {
/**
* #Rest\View()
* #Rest\Get("/apitest")
*/
public function indexAction()
{
$apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$apisecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
$mj = new \Mailjet\Client($apikey, $apisecret);
$id=17361101;
$Data = $mj->get(Resources::$Message, ['id' => $id]);
$Data= $Data->getData();
return $Data;}
The Response Json:
[{"ArrivedAt":"2016-05-13T07:34:47Z","AttachmentCount":0,"AttemptCount":0,"CampaignID":4884268551,"ContactID":1690868613,"Delay":0,"DestinationID":12344543,"FilterTime":61,"ID":17361101,"IsClickTracked":true,"IsHTMLPartIncluded":true,"IsOpenTracked":true,"IsTextPartIncluded":false,"IsUnsubTracked":false,"MessageSize":19308,"SenderID":4294850021,"SpamassassinScore":0,"SpamassRules":"","StatePermanent":false,"Status":"clicked"}]
I created an entity message containing all the attributes of the Api response
<?php
namespace DashbordMailjetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Message
{
/**
* #ORM\Column(type="datetime" ,name="ArrivedAt")
*/
private $ArrivedAt;
/**
* #ORM\Column(type="bigint",name="AttachmentCount")
*/
private $AttachmentCount;
/**
* #ORM\Column(type="bigint",name="AttemptCount")
*/
private $AttemptCount;
/**
* #ORM\Column(type="bigint",name="CampaignID")
*/
private $CampaignID;
/**
* #ORM\Column(type="bigint",name="ContactID")
*/
private $ContactID;
/**
* #ORM\Column(type="bigint",name="Delay")
*/
private $Delay;
/**
* #ORM\Column(type="bigint",name="DestinationID")
*/
private $DestinationID;
/**
* #ORM\Column(type="bigint",name="FilterTime")
*/
private $FilterTime;
/**
* #var bigint $uid
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ID;
/**
* #ORM\Column(type="boolean",name="IsClickTracked")
*/
private $IsClickTracked;
/**
* #ORM\Column(type="boolean",name="IsHTMLPartIncluded")
*/
private $IsHTMLPartIncluded;
/**
* #ORM\Column(type="boolean",name="IsOpenTracked")
*/
private $IsOpenTracked;
/**
* #var boolean
*
* #ORM\Column(type="boolean",name="IsTextPartIncluded")
*/
private $IsTextPartIncluded;
/**
* #ORM\Column(type="boolean",name="IsUnsubTracked")
*/
private $IsUnsubTracked;
/**
* #ORM\Column(type="bigint",name="MessageSize")
*/
private $MessageSize;
/**
* #ORM\Column(type="bigint",name="SenderID")
*/
private $SenderID;
/**
* #ORM\Column(type="string",name="SpamassassinScore")
*/
private $SpamassassinScore;
/**
* #ORM\Column(type="string",name="SpamassRules", nullable=true)
*/
private $SpamassRules;
/**
* #ORM\Column(type="boolean",name="StatePermanent")
*/
private $StatePermanent;
/**
* #ORM\Column(type="string",name="Status")
*/
private $Status;
/**
* #return datetime
*/
public function getArrivedAt()
{
return $this->ArrivedAt;
}
/**
* #param datetime $ArrivedAt
*/
public function setArrivedAt($ArrivedAt)
{
$this->ArrivedAt = $ArrivedAt;
}
/**
* #return mixed
*/
public function getAttachmentCount()
{
return $this->AttachmentCount;
}
/**
* #param mixed $AttachmentCount
*/
public function setAttachmentCount($AttachmentCount)
{
$this->AttachmentCount = $AttachmentCount;
}
/**
* #return int
*/
public function getAttemptCount()
{
return $this->AttemptCount;
}
/**
* #param int $AttemptCount
*/
public function setAttemptCount($AttemptCount)
{
$this->AttemptCount = $AttemptCount;
}
/**
* #return int
*/
public function getCampaignID()
{
return $this->CampaignID;
}
/**
* #param int $CampaignID
*/
public function setCampaignID($CampaignID)
{
$this->CampaignID = $CampaignID;
}
/**
* #return int
*/
public function getContactID()
{
return $this->ContactID;
}
/**
* #param int $ContactID
*/
public function setContactID($ContactID)
{
$this->ContactID = $ContactID;
}
/**
* #return int
*/
public function getDelay()
{
return $this->Delay;
}
/**
* #param int $Delay
*/
public function setDelay($Delay)
{
$this->Delay = $Delay;
}
/**
* #return int
*/
public function getDestinationID()
{
return $this->DestinationID;
}
/**
* #param int $DestinationID
*/
public function setDestinationID($DestinationID)
{
$this->DestinationID = $DestinationID;
}
/**
* #return int
*/
public function getFilterTime()
{
return $this->FilterTime;
}
/**
* #param int $FilterTime
*/
public function setFilterTime($FilterTime)
{
$this->FilterTime = $FilterTime;
}
/**
* #return mixed
*/
public function getID()
{
return $this->ID;
}
/**
* #param mixed $ID
*/
public function setID($ID)
{
$this->ID = $ID;
}
/**
* #return boolean
*/
public function isIsClickTracked()
{
return $this->IsClickTracked;
}
/**
* #param boolean $IsClickTracked
*/
public function setIsClickTracked($IsClickTracked)
{
$this->IsClickTracked = $IsClickTracked;
}
/**
* #return boolean
*/
public function isIsHTMLPartIncluded()
{
return $this->IsHTMLPartIncluded;
}
/**
* #param boolean $IsHTMLPartIncluded
*/
public function setIsHTMLPartIncluded($IsHTMLPartIncluded)
{
$this->IsHTMLPartIncluded = $IsHTMLPartIncluded;
}
/**
* #return boolean
*/
public function isIsOpenTracked()
{
return $this->IsOpenTracked;
}
/**
* #param boolean $IsOpenTracked
*/
public function setIsOpenTracked($IsOpenTracked)
{
$this->IsOpenTracked = $IsOpenTracked;
}
/**
* #return boolean
*/
public function isIsTextPartIncluded()
{
return $this->IsTextPartIncluded;
}
/**
* #param boolean $IsTextPartIncluded
*/
public function setIsTextPartIncluded($IsTextPartIncluded)
{
$this->IsTextPartIncluded = $IsTextPartIncluded;
}
/**
* #return boolean
*/
public function isIsUnsubTracked()
{
return $this->IsUnsubTracked;
}
/**
* #param boolean $IsUnsubTracked
*/
public function setIsUnsubTracked($IsUnsubTracked)
{
$this->IsUnsubTracked = $IsUnsubTracked;
}
/**
* #return int
*/
public function getMessageSize()
{
return $this->MessageSize;
}
/**
* #param int $MessageSize
*/
public function setMessageSize($MessageSize)
{
$this->MessageSize = $MessageSize;
}
/**
* #return int
*/
public function getSenderID()
{
return $this->SenderID;
}
/**
* #param int $SenderID
*/
public function setSenderID($SenderID)
{
$this->SenderID = $SenderID;
}
/**
* #return string
*/
public function getSpamassassinScore()
{
return $this->SpamassassinScore;
}
/**
* #param string $SpamassassinScore
*/
public function setSpamassassinScore($SpamassassinScore)
{
$this->SpamassassinScore = $SpamassassinScore;
}
/**
* #return string
*/
public function getSpamassRules()
{
return $this->SpamassRules;
}
/**
* #param string $SpamassRules
*/
public function setSpamassRules($SpamassRules)
{
$this->SpamassRules = $SpamassRules;
}
/**
* #return boolean
*/
public function isStatePermanent()
{
return $this->StatePermanent;
}
/**
* #param boolean $StatePermanent
*/
public function setStatePermanent($StatePermanent)
{
$this->StatePermanent = $StatePermanent;
}
/**
* #return string
*/
public function getStatus()
{
return $this->Status;
}
/**
* #param string $Status
*/
public function setStatus($Status)
{
$this->Status = $Status;
}}
I'am Trying to deserialize the api response in a message object
<?php
namespace DashbordMailjetBundle\Controller;
use DashbordMailjetBundle\Entity\Message;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use \Mailjet\Resources;
use JMS\Serializer\SerializerBuilder;
class DefaultController extends FOSRestController
{
/**
* #Rest\View()
* #Rest\Get("/apitest")
*/
public function indexAction()
{
$apikey = 'xxxxxxxxxxxxxxxxxxxx';
$apisecret = 'xxxxxxxxxxxxxxxxxxxxx';
$mj = new \Mailjet\Client($apikey, $apisecret);
$id=17361101;
$Data = $mj->get(Resources::$Message, ['id' => $id]);
$Data= $Data->getData();
$serializer = SerializerBuilder::create()->build();
$msg=$serializer->deserialize($Data, 'DashbordMailjetBundle\Entity \Message', 'json');
$em = $this->getDoctrine()->getManager();
$em->persist($msg);
return $msg;
}
But I have this error : Warning: json_decode() expects parameter 1 to be string, array given, Any help ?
{"error":{"code":500,"message":"Internal Server Error","exception": [{"message":"Warning: json_decode() expects parameter 1 to be string, array given","class":"Symfony\\Component\\Debug\\Exception\\ContextErrorException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"\/home\/chayma\/my_project_name\/vendor\/jms\/serializer\/src\/JMS\/Serializer\/JsonDeserializationVisitor.php","line":27,"args":[]},{"namespace":"Symfony\\Component\\Debug","short_class":"ErrorHandler","class":"Symfony\\Component\\Debug\\ErrorHandler","type":"->","function":"handleError","file":null,"line":null,"args":[["string","2"],["string","json_decode() expects parameter 1 to be string, array given"],["string","\/home\/chayma\/my_project_name\/vendor\/jms\/serializer\/src\/JMS\/Serializer\/JsonDeserializationVisitor.php"],["string","27"],["array",{"str":["array",[["array",{"ArrivedAt":["string","2016-05-13T07:34:47Z"],"AttachmentCount":["string","0"],"AttemptCount":["string","0"],"CampaignID":["string","4884268551"],"ContactID":["string","1690868613"],"Delay":["string","0"],"DestinationID":["string","12344543"],"FilterTime":["string","61"],"ID":["string","17361101"],"IsClickTracked":["boolean",true],"IsHTMLPartIncluded":["boolean",true],"IsOpenTracked":["boolean",true],"IsTextPartIncluded":["boolean",false],"IsUnsubTracked":["boolean",false],"MessageSize":["string","19308"],"SenderID":["string","4294850021"],"SpamassassinScore":["string","0"],"SpamassRules":["string",""],"StatePermanent":["boolean",false],"Status":["string","clicked"]}]]]}]]},
As said supra, the serializer is expecting a string, but, if I print the result of $Data->getData(), I get an array, such as the one below:
Array
(
[0] => Array
(
[ArrivedAt] => 2017-02-15T10:01:00Z
[AttachmentCount] => 0
[AttemptCount] => 0
[CampaignID] => 5946xxxxxx
[ContactID] => 1725xxxxxx
[Delay] => 0
[DestinationID] => 14
[FilterTime] => 111
[ID] => 16888626888xxxxxx
[IsClickTracked] =>
[IsHTMLPartIncluded] => 1
[IsOpenTracked] => 1
[IsTextPartIncluded] => 1
[IsUnsubTracked] =>
[MessageSize] => 2213
[SenderID] => 4863xxxxxx
[SpamassassinScore] => 0
[SpamassRules] =>
[StatePermanent] =>
[Status] => opened
)
)
I'd advise you to look at the repository of the PHP wrapper, or at the documentation for PHP users.
hAPI coding!
Disclaimer: Mailjet's employee here.
As defined in the serializer documentation, $serializer->deserialize() expects a string.
It seems that your $Data->getData(); returns an array. (that's what the error message is telling you ;D )

Many-to-many relationship inside a symfony 3 form

I have a problem implementing a symfony 3 form with two objects having a many-to-many relationship.
I have two datatables, "Users" and "Roles". I want to have a form, where I can edit a user and assign a user some roles. In detail I want a form where each Role is a checkbox and I can choose which role a user has.
I know, that I have to implement a new UserType,, but how can I implement the dynamic checkboxes?
This is my User-Class:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Table(name="app_users")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="user_roles")
*/
private $roles;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
$permissionsArray = array();
foreach ($this->roles as $role)
{
$rolesPermissions = $role->getPermissions();
for($i=0;$i<count($rolesPermissions);$i++)
if(!in_array($rolesPermissions[$i],$permissionsArray))
$permissionsArray[] = $rolesPermissions[$i];
}
return $permissionsArray;
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* 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;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* 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 isActive
*
* #param boolean $isActive
*
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
}
And this is my Role-Class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="role")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RoleRepository")
*/
class Role
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="bezeichnung", type="string", length=255, unique=true)
*/
private $bezeichnung;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
/**
* #ORM\ManyToMany(targetEntity="Permission", inversedBy="roles")
* #ORM\JoinTable(name="roles_permissions")
*/
private $permissions;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set bezeichnung
*
* #param string $description
*
* #return Role
*/
public function setBezeichnung($bezeichnung)
{
$this->bezeichnung = $bezeichnung;
return $this;
}
/**
* Get bezeichnung
*
* #return string
*/
public function getBezeichnung()
{
return $this->bezeichnung;
}
/**
* Constructor
*/
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add user
*
* #param \AppBundle\Entity\User $user
*
* #return Role
*/
public function addUser(\AppBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AppBundle\Entity\User $user
*/
public function removeUser(\AppBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Add permission
*
* #param \AppBundle\Entity\Permission $permission
*
* #return Role
*/
public function addPermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions[] = $permission;
return $this;
}
/**
* Remove permission
*
* #param \AppBundle\Entity\Permission $permission
*/
public function removePermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions->removeElement($permission);
}
/**
* Get permissions
*
* #return Array
*/
public function getPermissions()
{
$permissionsArray = array();
foreach ($this->permissions as $permission)
$permissionsArray[] = "ROLE_".$permission->getTechBezeichnung();
return $permissionsArray;
}
}
a) Give your entities a __toString() method.
b) Make a UserType. You can also Use the CLI command bin/console doctrine:generate:crud and choose at "write actions" [yes].
The script wil generate a controller, a formType and some templates.
c) add this use statement at the top of UserType:
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
d) add this formfield into your UserType:
->add('roles', EntityType::class, array(
'expanded => true,
'multiple' => true
))

500: Internal Server Error undefined index Symfony3

I'm trying to send from api rest controller (Symfony3) a object collection but get an error. "{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"Notice: Undefined index: Bar"
/**
*
*
* #Get("/api/bars.{_format}", defaults={"_format"="json"}, options={"expose"=true}, name="api_bars")
* #View()
*/
public function getBarsAction (Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('Session');
$repository = $em->getRepository('AppBundle:Bar');
$bars = $repository->findAll();
foreach ($bars as $bar)
{
$id = $bar->getId();
$name = $bar->getName();
$bars[] = array('id'=>$id,'name'=>$name);
}
$view = $this->View($bars,200);
return $this->handleView($view);
}
And the Bar Entity is:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Bar
*
* #ORM\Table(name="Bar")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BarRepository")
*/
class Bar
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=45, nullable=true)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=45, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
public function __construct()
{
$this->waiters = new ArrayCollection();
$this->tables = new ArrayCollection();
$this->stockfoods = new ArrayCollection();
$this->stockdrinks = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Bar
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set location
*
* #param string $location
*
* #return Bar
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set description
*
* #param string $description
*
* #return Bar
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
public function addWaiter($value){
$this->waiters[] = $value;
}
public function getWaiters(){
return $this->waiters;
}
public function removeWaiters($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->waiters->removeElement($id);
}
public function addTable($value){
$this->tables[] = $value;
}
public function getTables(){
return $this->tables;
}
public function removeTables($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->tables->removeElement($id);
}
public function addFood($value){
$this->stockfoods[] = $value;
}
public function getFoods(){
return $this->stockfoods;
}
public function removeFoods($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockfoods->removeElement($id);
}
public function addDrink($value){
$this->stockdrinks[] = $value;
}
public function getDrinks(){
return $this->stockdrinks;
}
public function removeDrinks($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockdrinks->removeElement($id);
}
}
Thanks a lot!!!!
I solved my problem!!! I was related to association mapping. I've changed this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
For this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="bar") */
private $stockdrinks;

Doctrine 2: JOIN query not working

The query below is not giving any result.
$query = $this->em->createQuery("
SELECT cs, cc
FROM App\Entity\Continents cs
JOIN cs.countries cc
WHERE cs.enabled = 1 AND cs.deleted = 0
");
If I print the query using "print_r($query);" it prints the object... but if I try to get the sql using "print($query->getSQL());" it doesn't work.
Any help will be much appreciated.
Please note: it works fine without the join.
The entity mapping
Countries Entity
/**
* #Entity(repositoryClass="App\Repository\Continents")
* #Table(name="countries")
*/
class Countries {
/**
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Continents", inversedBy="countries")
* #ORM\JoinColumn(name="id", referencedColumnName="continent_id")
*/
protected $continents;
/** #Column(type="integer", length=1) */
protected $continent_id;
/** #Column(type="string", length=3) */
protected $iso_number;
/** #Column(type="string", length=2) */
protected $iso_2_code;
/** #Column(type="string", length=3) */
protected $iso_3_code;
/** #Column(type="string", length=45) */
protected $name;
/** #Column(type="string", length=3) */
protected $default_currency;
/** #Column(type="string", length=3) */
protected $currency_symbol;
/** #Column(type="integer", length=3) */
protected $currency_id;
/** #Column(type="integer", length=1) */
protected $postcode_check;
/** #Column(type="string", length=150) */
protected $postcode_regex;
/** #Column(type="integer", length=1) */
protected $enabled;
/** #Column(type="integer", length=1) */
protected $deleted;
/** #Column(type="datetime") */
protected $created;
/** #Column(type="integer", length=11) */
protected $created_by;
/** #Column(type="datetime") */
protected $modified;
/** #Column(type="integer", length=11) */
protected $modified_by;
public function __construct() {
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getContinents() {
return $this->continents;
}
public function setContinents(\App\Entity\Continents $continents) {
$this->continents = $continents;
}
public function getContinent_id() {
return $this->continent_id;
}
public function setContinent_id($continent_id) {
$this->continent_id = $continent_id;
}
public function getIso_number() {
return $this->iso_number;
}
public function setIso_number($iso_number) {
$this->iso_number = $iso_number;
}
public function getIso_2_code() {
return $this->iso_2_code;
}
public function setIso_2_code($iso_2_code) {
$this->iso_2_code = $iso_2_code;
}
public function getIso_3_code() {
return $this->iso_3_code;
}
public function setIso_3_code($iso_3_code) {
$this->iso_3_code = $iso_3_code;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getDefault_currency() {
return $this->default_currency;
}
public function setDefault_currency($default_currency) {
$this->default_currency = $default_currency;
}
public function getCurrency_symbol() {
return $this->currency_symbol;
}
public function setCurrency_symbol($currency_symbol) {
$this->currency_symbol = $currency_symbol;
}
public function getCurrency_id() {
return $this->currency_id;
}
public function setCurrency_id($currency_id) {
$this->currency_id = $currency_id;
}
public function getPostcode_check() {
return $this->postcode_check;
}
public function setPostcode_check($postcode_check) {
$this->postcode_check = $postcode_check;
}
public function getPostcode_regex() {
return $this->postcode_regex;
}
public function setPostcode_regex($postcode_regex) {
$this->postcode_regex = $postcode_regex;
}
public function getEnabled() {
return $this->enabled;
}
public function setEnabled($enabled) {
$this->enabled = $enabled;
}
public function getDeleted() {
return $this->deleted;
}
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
public function getCreated() {
return $this->created;
}
public function setCreated($created) {
$this->created = $created;
}
public function getModified() {
return $this->modified;
}
public function setModified($modified) {
$this->modified = $modified;
}
public function getCreated_by() {
return $this->created_by;
}
public function setCreated_by($created_by) {
$this->created_by = $created_by;
}
public function getModified_by() {
return $this->modified_by;
}
public function setModified_by($modified_by) {
$this->modified_by = $modified_by;
}
}
Continents Entity
/**
* #Entity
* #Table(name="continents")
*/
class Continents {
/**
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Countries", mappedBy="continents")
*/
protected $countries;
/** #Column(type="string", length=7) */
protected $name;
/** #Column(type="integer", length=1) */
protected $enabled;
/** #Column(type="integer", length=1) */
protected $deleted;
/** #Column(type="datetime") */
protected $created;
/** #Column(type="integer", length=11) */
protected $created_by;
/** #Column(type="datetime") */
protected $modified;
/** #Column(type="integer", length=11) */
protected $modified_by;
public function __construct() {
$this->countries = new ArrayCollection();
}
public function getCountries() {
return $this->countries;
}
public function setCountries($countries) {
$this->countries = $countries;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getCreated_by() {
return $this->created_by;
}
public function setCreated_by($created_by) {
$this->created_by = $created_by;
}
public function getModified_by() {
return $this->modified_by;
}
public function setModified_by($modified_by) {
$this->modified_by = $modified_by;
}
public function getEnabled() {
return $this->enabled;
}
public function setEnabled($enabled) {
$this->enabled = $enabled;
}
public function getDeleted() {
return $this->deleted;
}
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
public function getCreated() {
return $this->created;
}
public function setCreated($created) {
$this->created = $created;
}
public function getModified() {
return $this->modified;
}
public function setModified($modified) {
$this->modified = $modified;
}
}
i dont know what this column name you have but you should escape it by backticks like that:
SELECT cs.* , cc.* -- //--you are selecting tables.
FROM `Continents` cs --escape by backticks here
JOIN countries cc --no need cs here
ON ............ --condition here (relation between the two tables)
WHERE cs.enabled = 1 AND cs.deleted = 0 --this is good
This issue has been fixed. The problem was in my Entities. I updated my continents and countries entities as below and it worked fine. I hope this will help someone else.
/**
* #Entity(repositoryClass="App\Repository\Continents")
* #Table(name="continents")
*/
class Continents {
/**
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Countries", mappedBy="continents")
*/
protected $countries;
/** #Column(type="string", length=7) */
protected $name;
/** #Column(type="integer", length=1) */
protected $enabled;
/** #Column(type="integer", length=1) */
protected $deleted;
/** #Column(type="datetime") */
protected $created;
/** #Column(type="integer", length=11) */
protected $created_by;
/** #Column(type="datetime") */
protected $modified;
/** #Column(type="integer", length=11) */
protected $modified_by;
public function __construct() {
$this->countries = new ArrayCollection();
}
public function getCountries() {
return $this->countries;
}
public function setCountries($countries) {
$this->countries = $countries;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getCreated_by() {
return $this->created_by;
}
public function setCreated_by($created_by) {
$this->created_by = $created_by;
}
public function getModified_by() {
return $this->modified_by;
}
public function setModified_by($modified_by) {
$this->modified_by = $modified_by;
}
public function getEnabled() {
return $this->enabled;
}
public function setEnabled($enabled) {
$this->enabled = $enabled;
}
public function getDeleted() {
return $this->deleted;
}
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
public function getCreated() {
return $this->created;
}
public function setCreated($created) {
$this->created = $created;
}
public function getModified() {
return $this->modified;
}
public function setModified($modified) {
$this->modified = $modified;
}
}
/**
* #Entity(repositoryClass="App\Repository\Continents")
* #Table(name="countries")
*/
class Countries {
/**
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Continents", inversedBy="countries")
* #ORM\JoinColumn(name="continent_id", referencedColumnName="id")
*/
protected $continents;
/** #Column(type="integer", length=1) */
protected $continent_id;
/** #Column(type="string", length=3) */
protected $iso_number;
/** #Column(type="string", length=2) */
protected $iso_2_code;
/** #Column(type="string", length=3) */
protected $iso_3_code;
/** #Column(type="string", length=45) */
protected $name;
/** #Column(type="string", length=3) */
protected $default_currency;
/** #Column(type="string", length=3) */
protected $currency_symbol;
/** #Column(type="integer", length=3) */
protected $currency_id;
/** #Column(type="integer", length=1) */
protected $postcode_check;
/** #Column(type="string", length=150) */
protected $postcode_regex;
/** #Column(type="integer", length=1) */
protected $enabled;
/** #Column(type="integer", length=1) */
protected $deleted;
/** #Column(type="datetime") */
protected $created;
/** #Column(type="integer", length=11) */
protected $created_by;
/** #Column(type="datetime") */
protected $modified;
/** #Column(type="integer", length=11) */
protected $modified_by;
public function __construct() {
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getContinents() {
return $this->continents;
}
public function setContinents(\App\Entity\Continents $continents) {
$this->continents = $continents;
}
public function getContinent_id() {
return $this->continent_id;
}
public function setContinent_id($continent_id) {
$this->continent_id = $continent_id;
}
public function getIso_number() {
return $this->iso_number;
}
public function setIso_number($iso_number) {
$this->iso_number = $iso_number;
}
public function getIso_2_code() {
return $this->iso_2_code;
}
public function setIso_2_code($iso_2_code) {
$this->iso_2_code = $iso_2_code;
}
public function getIso_3_code() {
return $this->iso_3_code;
}
public function setIso_3_code($iso_3_code) {
$this->iso_3_code = $iso_3_code;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getDefault_currency() {
return $this->default_currency;
}
public function setDefault_currency($default_currency) {
$this->default_currency = $default_currency;
}
public function getCurrency_symbol() {
return $this->currency_symbol;
}
public function setCurrency_symbol($currency_symbol) {
$this->currency_symbol = $currency_symbol;
}
public function getCurrency_id() {
return $this->currency_id;
}
public function setCurrency_id($currency_id) {
$this->currency_id = $currency_id;
}
public function getPostcode_check() {
return $this->postcode_check;
}
public function setPostcode_check($postcode_check) {
$this->postcode_check = $postcode_check;
}
public function getPostcode_regex() {
return $this->postcode_regex;
}
public function setPostcode_regex($postcode_regex) {
$this->postcode_regex = $postcode_regex;
}
public function getEnabled() {
return $this->enabled;
}
public function setEnabled($enabled) {
$this->enabled = $enabled;
}
public function getDeleted() {
return $this->deleted;
}
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
public function getCreated() {
return $this->created;
}
public function setCreated($created) {
$this->created = $created;
}
public function getModified() {
return $this->modified;
}
public function setModified($modified) {
$this->modified = $modified;
}
public function getCreated_by() {
return $this->created_by;
}
public function setCreated_by($created_by) {
$this->created_by = $created_by;
}
public function getModified_by() {
return $this->modified_by;
}
public function setModified_by($modified_by) {
$this->modified_by = $modified_by;
}
}