I have a entity :
/**
* #ORM\Entity
* #ORM\Table(name="organization")
*/
class Organization
{
/*
*#ORM\OneToMany(targetEntity="Link" , mappedBy="organization")
*/
private $links;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Organization
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set site
*
* #param string $site
* #return Organization
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Get site
*
* #return string
*/
public function getSite()
{
return $this->site;
}
public function __construct()
{
$this->links = new ArrayCollection();
}
}
when run command :
php console doctrine:generate:entities News/VillageNewsBundle/Entity/Organization
when i run this command all the getter and setter
will generated but getter and setter for relation not add to my entity?!
That's because your OneToMany annotation is wrong.
You must use the correct doc synthax, which is:
/**
* [...]
*/
Here, it misses one '*' before your OneToMany annotation. Add it and it will work. :-)
Related
I have two entities:
TicketEntity :
/**
* #ORM\MappedSuperclass()
*/
class Ticket implements TicketInterface
{
const DIR_UPLOAD = 'TicketUpload';
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Attachment", mappedBy="ticket", cascade={"remove"}, orphanRemoval=true)
*/
protected $attachments;
/**
* Ticket constructor.
*/
public function __construct()
{
$this->attachments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* Add attachments
*
* #param Attachment $attachments
* #return Ticket
*/
public function addAttachment(Attachment $attachments)
{
$this->attachments[] = $attachments;
return $this;
}
/**
* Remove attachments
*
* #param Attachment $attachments
*/
public function removeAttachment(Attachment $attachments)
{
$this->attachments->removeElement($attachments);
}
/**
* Get attachments
*
* #return Collection
*/
public function getAttachments()
{
return $this->attachments;
}
}
AttachmentEntity:
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\AttachmentRepository")
* #ORM\Table(name="ticket_attachments")
*/
class Attachment
{
const DIR_UPLOAD = 'TicketUpload';
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
* #ORM\Column(type="text", nullable=true)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Ticket", inversedBy="attachments")
* #ORM\JoinColumn(name="ticket_id", referencedColumnName="id", nullable=true)
*/
protected $ticket;
/**
* #Assert\File(
* maxSize = "300k",
* mimeTypes = {"application/pdf", "application/x-pdf", "text/plain", "application/msword",
* "application/vnd.ms-excel", "image/jpeg", "image/x-citrix-jpeg", "image/png", "image/x-citrix-png", "image/x-png", "image/gif"},
* mimeTypesMessage = "Liste de formats de fichiers acceptés : .pdf,.txt,.doc,.xls,.jpg,.png,.gif"
* )
*/
private $attachmentFile;
/**
* #ORM\Column(type="string", nullable=true)
*
*/
private $attachment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name): self
{
$this->name = $name;
return $this;
}
public function getTicket(): ?Ticket
{
return $this->ticket;
}
public function setTicket(Ticket $ticket): void
{
$this->ticket = $ticket;
}
/**
* #return mixed
*/
public function getAttachment(): ?string
{
return $this->attachment;
}
public function setAttachment($attachment): self
{
$this->attachment = $attachment;
return $this;
}
public function getAttachmentFile(): ?UploadedFile
{
return $this->attachmentFile;
}
/**
* #param $attachmentFile
* #return Ticket
*/
public function setAttachmentFile($attachmentFile): self
{
$this->attachmentFile = $attachmentFile;
return $this;
}
public function getAttachmentWebPath()
{
return self::DIR_UPLOAD . '/' . $this->getAttachment();
}
}
My goal is that a ticket can have several attachments.
And I have this error:
The association AppBundle\Entity\Attachment#ticket refers to the
inverse side field AppBundle\Entity\Ticket#attachments which does not
exist.
I don't know where I'm wrong... Anyone know ?
Regards
mapped superclasses are really inconvenient. really. (emphasis mine)
A mapped superclass cannot be an entity, it is not query-able and
persistent relationships defined by a mapped superclass must be
unidirectional (with an owning side only). This means that One-To-Many
associations are not possible on a mapped superclass at all.
Furthermore Many-To-Many associations are only possible if the mapped
superclass is only used in exactly one entity at the moment. For
further support of inheritance, the single or joined table inheritance
features have to be used.
so, you're not technically doing something wrong, it just isn't supported at all. The error message produced isn't helpful at all though...
I'm developing a rest api application with symfony in backend.
My problem is that when I try to lauch a GET request, the application runs without giving any response even after even after some ten minutes.
this is the request method:
/**
* CounterRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CounterRepository extends \Doctrine\ORM\EntityRepository
{
/**
* #param string $name
* #param int $date
* #return mixed
* #throws \Exception
*/
public function getValuesByNameAndDate(string $name, int $date)
{
$query = $this
->createQueryBuilder('c')
->leftJoin('c.values', 'v', 'WITH')
->addSelect('v')
->where('c.name = :name')
->andWhere('v.date = :date')
->setParameters(
array(
'date' => $date,
'name' => $name
)
)
->getQuery();
return $query->getResult();
}
}
The CounterValue Entity:
/**
* CounterValue
*
* #ORM\Table(name="counter_value")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CounterValueRepository")
*/
class CounterValue
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="value", type="float")
*/
private $value;
/**
* #var int
*
* #ORM\Column(name="date", type="integer")
*/
private $date;
/**
* #var Counter
*
* #ORM\ManyToOne(targetEntity="Counter", inversedBy="values")
* #ORM\JoinColumn()
*/
private $counter;
/**
* #var City
*
* #ORM\ManyToOne(targetEntity="City", inversedBy="values"))
* #ORM\JoinColumn()
*/
protected $city;
public function __construct()
{
$date = new \DateTime('-1 day');
$this->date = strtotime($date->format('d-m-Y'));
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set value.
*
* #param float $value
*
* #return CounterValue
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value.
*
* #return float
*/
public function getValue()
{
return $this->value;
}
/**
* Set date.
*
* #param int $date
*
* #return CounterValue
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date.
*
* #return int
*/
public function getDate()
{
return $this->date;
}
/**
* #return Counter
*/
public function getCounter(): Counter
{
return $this->counter;
}
/**
* #param Counter $counter
*/
public function setCounter(Counter $counter): void
{
$this->counter = $counter;
}
/**
* #return City
*/
public function getCity(): City
{
return $this->city;
}
/**
* #param City $city
*/
public function setCity(City $city): void
{
$this->city = $city;
}
}
/**
* Counter
*
* #ORM\Table(name="counter")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CounterRepository")
*/
class Counter
{
/**
* #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=255, unique=false)
*/
private $name;
/**
* #var XmlFile
*
* #ORM\ManyToOne(targetEntity="XmlFile", inversedBy="counters", cascade={"remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $xmlFile;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="CounterValue", mappedBy="counter", cascade={"persist"})
*/
private $values;
public function __construct()
{
$this->values = new ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name.
*
* #param string $name
*
* #return Counter
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name.
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set xmlFile
*
* #param XmlFile $xmlFile
*/
public function setXmlFile(XmlFile $xmlFile)
{
$this->xmlFile = $xmlFile;
}
/**
* Get xmlFile
*
* #return XmlFile
*/
public function getXmlFile(): XmlFile
{
return $this->xmlFile;
}
/**
* #return ArrayCollection
*/
public function getValues(): ArrayCollection
{
return $this->values;
}
/**
* #param ArrayCollection $values
*/
public function setValues(ArrayCollection $values): void
{
$this->values = $values;
}
/**
* Add $value
*
* #param CounterValue $value
*/
public function addValue(CounterValue $value)
{
$value->setCounter($this);
if(!$this->values->contains($value)){
$this->values->add($value);
}
}
}
And finally my method in controller
$em = $this->get('doctrine.orm.entity_manager');
$counterRep = $em->getRepository('AppBundle:Counter');
return $counterRep->getValuesByNameAndDate('L.IRATHO.E2G.CSFB.ExecSuccOut', 1533600000);
Just return a Json response like this.
public function listAction(Request $request)
{
try
{
$em = $this->get('doctrine.orm.entity_manager');
$counterRep = $em->getRepository('AppBundle:Counter')->getValuesByNameAndDate('L.IRATHO.E2G.CSFB.ExecSuccOut', 1533600000);
return new JsonResponse(['success' => true, 'code' => Response::HTTP_OK, 'data' => $counterRep]);
}
catch (\Exception $exception)
{
return new JsonResponse(['success' => false,'code' => $exception->getCode() ,'message' => $exception->getMessage()]);
}
}
Controller action should return instance of
Symfony\Component\HttpFoundation\Response
You try to return result of query builder $query->getResult()
You need to change it to something like
public function counterValuesAction(Request $request) {
try {
$em = $this->get('doctrine.orm.entity_manager');
$counterRep = $em->getRepository('AppBundle:Counter');
$values = $counterRep->getValuesByNameAndDate('L.IRATHO.E2G.CSFB.ExecSuccOut', 1533600000);
} catch (\Exception $e) {
return new Response($values);
}
}
Solution for Symfony 4+:
<?php
namespace App\Controller;
class CounterController extends AbstractController
{
public function listAction(
CounterRepository $repository // DI works like this in Controllers...
) {
$result = $repository->getValuesByNameAndDate('L.IRATHO.E2G.CSFB.ExecSuccOut', 1533600000);
// use JsonResponse object to create JSON response
return $this->json($result, Response::HTTP_OK);
}
}
// routes.yaml
counter_list:
path: /counter
controller: App\Controller\CounterController::listAction
methods: GET
Clear cache and try to send GET request to http://your-dev-host/counter
How does it work?
Controller
You need to create controller CounterController class with action function listAction. It is good practice to add Action postfix to action function.
You can define services or other DI objects as parameters in action functions. DI will set it. For example:
class MyController extends AbstractController
{
public function listAction(
Request $request,
SerializerInterface $serializer,
ValidatorInterface $validator,
CounterRepository $repository
) {
// ...
}
}
In order to send good response with JSON and all headers that is needed you need to use AbstractController::json function. It creates JsonResponse object. You can check it implementation.
More information about symfony controllers you can find in this article https://symfony.com/doc/current/controller.html
Routing
Next step is to create route for your new controller action. You can do it in 2 ways:
Adding record to config/routes.yaml file as i did
Use annotations (Annotations is bad practice because comments should not break programm)
More information about routing you can find in this article https://symfony.com/doc/current/routing.html
It does not work for me! How can I debug it?
First, dont panic and read error message. Also, you can check if routing works well. You can do it using command
$ bin/console debug:router
----------------------- -------- -------- ------ -------------------------------------
Name Method Scheme Host Path
----------------------- -------- -------- ------ -------------------------------------
_preview_error ANY ANY ANY /_error/{code}.{_format}
register_token POST ANY ANY /auth/register
refresh_token POST ANY ANY /auth/refresh
auth_login POST ANY ANY /auth/login
restroom_list GET ANY ANY /api/v1/restroom
----------------------- -------- -------- ------ -------------------------------------
In table you need to check your new url and how Symfony sees it.
Second, try to send request to this URL using curl and check response.
$ curl http://localhost/auth/login
I hope I can be clear in my question.
In my symfony2 project I'm following this tutorial to make a form in which I can press the link to add as many "auteur" as the user wants, so I tried to do it with form collection.
Everything works fine, except the many to one field that always gets "null" value and not the "id".
Here is what I have done.
Soumission entity in which I have the add "auteur" link
....
/**
* #ORM\OneToMany(targetEntity="tuto\BackofficeBundle\Entity\Auteur",
mappedBy="soumission", cascade={"persist"})
*/
protected $auteurs;
.....
/**
* #param Collection $auteurs
* #return $this
*/
public function setAuteurs(Collection $auteurs)
{
$this->auteurs = $auteurs;
return $this;
}
/**
* Add auteur
*
* #param \tuto\BackofficeBundle\Entity\Auteur $auteur
* #return Soumission
*/
public function addAuteur(Auteur $auteur)
{
if ( ! $this->auteurs->contains($auteur) ) {
$auteur->setSoumission($this); // this should set the "soumission-
id" field
$this->auteurs->add($auteur);
}
return $this->auteurs;
}
public function removeAuteur(Auteur $auteur)
{
if ($this->auteurs->contains($auteur)) {
$this->auteurs->removeElement($auteur);
}
return $this->auteurs;
}
/**
* #return mixed
*/
public function getAuteurs()
{
return $this->auteurs;
}
This is the auteur entity:
/**
* #ORM\ManyToOne(targetEntity="Soumission", inversedBy="auteur")
* #ORM\JoinColumn(name="soumission_id", referencedColumnName="id")
*/
protected $Soumission;
/**
* #param $soumission
* #return $this
*/
public function setSoumission(Soumission $soumission)
{
$this->soumission = $soumission;
return $this;}
/**
* #return mixed
*/
public function getSoumission()
{
return $this->soumission;
}
public function __toString() {
return $this->Soumission;
}
the result should be like the second line and not null value
try to do this :
/**
* #ORM\OneToMany(targetEntity="Auteur",mappedBy="soumission", cascade={"persist"})
*/
protected $auteurs;
/**
* Add auteurs
* #return FormationMsk
*/
public function addAuteur(\tuto\BackofficeBundle\Entity\Auteur $auteurs)
{
$this->auteurs[] = $auteurs;
return $this;
}
/**
* Remove auteurs
*/
public function removeAuteur(\tuto\BackofficeBundle\Entity\Auteur $auteurs)
{
$this->auteurs->removeElement($auteurs);
}
/**
* Get auteurs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAuteurs()
{
return $this->auteurs;
}
public function __construct()
{
$this-auteurs = new \Doctrine\Common\Collections\ArrayCollection();
}
and for the auteur entity :
/**
* #ORM\ManyToOne(targetEntity="Soumission", inversedBy="auteurs")
* #ORM\JoinColumn(name="soumission_id", referencedColumnName="id")
*/
protected $soumission;
I'm adding oneToMany relationship to database, and its working but when i want to view array i get this error :
Warning: Invalid argument supplied for foreach()
this is my User.php
class User implements AdvancedUserInterface, \Serializable
{
// ...
/**
* #ORM\OneToMany(targetEntity="Acme\CityBundle\Entity\City", mappedBy="user")
**/
private $cities;
public function __construct()
{
$this->cities = new ArrayCollection();
}
/**
* #inheritDoc
*/
public function getCities()
{
$c = array();
foreach ($this->cities as $city) {
$c[] = $city->getCity();
}
return $c;
}
/**
* Add cities
*
* #param \Acme\CityBundle\Entity\City $cities
* #return User
*/
public function addCity(\Acme\CityBundle\Entity\City $city)
{
$city->setUser($this);
$this->cities->add($city);
return $this->cities;
}
and City.php
<?php
namespace Acme\CityBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* City
*/
class City
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="cities")
* #JoinColumn(name="id", referencedColumnName="id")
**/
private $user;
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return City
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getCity()
{
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
Controller
$city=new City();
$em = $this->getDoctrine()->getManager();
$city->setName('Miasto');
$user->addCity($city);
$em->persist($city);
$em->persist($user);
$em->flush();
index controller
public function indexAction()
{
$cities=$this->get('security.context')->getToken()->getUser()->getCities();
return $this->render(
'AcmeUserBundle:User:index.html.twig',array( 'cities'=>$cities));
}
and when i try to show array (cities) in view i get error
Warning: Invalid argument supplied for foreach()
in User.php
foreach ($this->cities as $city)
my table city look (id,name)
Thanks for any help.
EDIT : SOLVED
I have to update my CityBundle\Resources\config\doctrine\City.orm.yml file
In your City class, shouldn't be the relationship something like :
/**
* #ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="cities")
* #JoinColumn(name="cityId", referencedColumnName="id")
**/
private $user;
The join column shouldn't be the id of user's table.
And then, of course:
public function getCities()
{
return $this->cities;
}
I have a problem while json_encodeing a Entity.
public function jsonvoteAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('KorumAGBundle:AGVote')->findOneById($id);
$response = new Response(json_encode($entity, 200));
$response->headers->set('Content-Type',' application/json');
return $response;
}
This code returns me a the users entity
{"users":{"__isInitialized__":false,"id":null,"nickname":null,"pwd":null,"email":null,"firstname":null,"lastname":null,"poste":null,"addr1":null,"addr2":null,"pc":null,"country":null,"phone":null,"province":null,"acess":null,"site":null,"crew":null,"utilisateur":null}}
And when I var dymp my $entity, it returns both my AGVote and USers entity.
Here is my AGVote Entity
<?php
namespace Korum\AGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Korum\AGBundle\Entity\AGVote
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class AGVote
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $question;
/**
* #ORM\Column(type="smallint")
*/
private $actif;
/**
* #ORM\ManyToOne(targetEntity="\Korum\KBundle\Entity\Users", cascade={"all"})
*/
public $users;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set question
* Nb : Only AG admin can set a question
* #param text $question
*/
public function setQuestion($question)
{
$this->question = $question;
}
/**
* Get question
*
* #return text
*/
public function getquestion()
{
return $this->question;
}
/**
* Set actif
*
* #param smallint $actif
*/
public function setActif($actif)
{
$this->actif = $actif;
}
/**
* Get actif
*
* #return smallint
*/
public function getActif()
{
return $this->actif;
}
/**
* Set Users
*
* #param Korum\KBundle\Entity\Province $Users
*/
public function setUsers(\Korum\KBundle\Entity\Users $users)
{
$this->users = $users;
}
/**
* Get Users
*
* #return Korum\KBundle\Entity\Users
*/
public function getUsers()
{
return $this->users;
}
}
Does anyone have an idea of what happened ?
I tried to install the JSMSerializerBundle but event with Metadata library at version 1.1.
When I want to clear my cache, it failed with error :
See :
JMSSerializerBundle Installation : Catchable Fatal Error: Argument 1 passed to JMSSerializerBundle\Twig\SerializerExtension::__construct()
By default, json_encode only uses public properties.
So it serialized the only public property of AGVote: $users. The content of $users was an instance of User; which public fields were serialized.
You could work around these by adding a toArray() method to your entities, and then doing json_encode($entity->toArray()), but i highly recommend you to have a look and use the JMSSerializedBundle.