Good day. There was such problem.
/**
* #ODM\Document
*/
class Post
{
/**
* #var string
*
* #ODM\Id
*/
private $id;
/**
* #var \DateTime
*
* #ODM\Date
*/
private $createdAt;
...
}
In controller persisted test document. At the base of enrolled:
{ "_id" : ObjectId("5603ece1147fe7322c8b4581"), "createdAt" : ISODate("2015-09-24T11:27:04Z") }
But when I make a selection from the controller, I get a null in createdAt:
Test {#531 ▼
-id: "5603ece1147fe7322c8b4581"
-createdAt: null
}
createdAt is not initialized. You can set it's value in the constructor.
public function __construct() {
$this->createdAt = new \DateTime("now");
}
Related
I'm facing issues with easy query to API-PLATFROM.
GraphQL Playground:
{
users{
edges{
node{
id
email
isActive
}
}
}
}
error:
"debugMessage": "Cannot return null for non-nullable field User.isActive.", same error I've got for createdAt filed.
Symfony entity:
<?php
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ApiResource(
* normalizationContext={"groups"={"read"}},
* denormalizationContext={"groups"={"write"}}
* )
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
* #Assert\NotNull
* #Assert\Email
* #Groups({"read","write"})
*/
private $email;
/**
* #ORM\Column(type="boolean")
* #Assert\NotNull
* #Groups({"read","write"})
*/
private $isActive;
public function getIsActive(): bool
{
return $this->isActive;
}
public function setIsActive(bool $isActive): self
{
$this->isActive = $isActive;
return $this;
}
}
Of course, I've got other getters and setters. When I change the query for example to return id and email, everything works correctly.
Have the following Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
/**
* Address
*
* #ApiResource(
* collectionOperations={"get"={"method"="GET"}},
* itemOperations={"get"={"method"="GET"}}
* )
* #ORM\Table(name="address")
* #ORM\Entity
*/
class Address
{
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #return string
*/
public function getLat(): string
{
return $this->lat;
}
/**
* #param string $lat
*/
public function setLat(string $lat): void
{
$this->lat = $lat;
}
/**
* #return string
*/
public function getLng(): string
{
return $this->lng;
}
/**
* #param string $lng
*/
public function setLng(string $lng): void
{
$this->lng = $lng;
}
/**
* #return string
*/
public function getStreet(): string
{
return $this->street;
}
/**
* #param string $street
*/
public function setStreet(string $street): void
{
$this->street = $street;
}
/**
* #return string
*/
public function getZipcode(): string
{
return $this->zipcode;
}
/**
* #param string $zipcode
*/
public function setZipcode(string $zipcode): void
{
$this->zipcode = $zipcode;
}
/**
* #return string
*/
public function getCity(): string
{
return $this->city;
}
/**
* #param string $city
*/
public function setCity(string $city): void
{
$this->city = $city;
}
/**
* #return string
*/
public function getDescription(): string
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription(string $description): void
{
$this->description = $description;
}
/**</h2>
* #var string
*
* #ORM\Column(name="lat", type="decimal", precision=10, scale=8, nullable=false)
*/
private $lat;
/**
* #var string
*
* #ORM\Column(name="lng", type="decimal", precision=10, scale=8, nullable=false)
*/
private $lng;
/**
* #var string
*
* #ORM\Column(name="street", type="string", length=255, nullable=false)
*/
private $street;
/**
* #var string
*
* #ORM\Column(name="zipcode", type="string", length=5, nullable=false)
*/
private $zipcode;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255, nullable=false)
*/
private $city;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
}
The table with one row of data:
I got this error:
"type": "https://www.rfc-editor.org/rfc/rfc2616#section-10",
"title": "An error occurred",
"detail": "Type error: Return value of App\Entity\Address::getLat() must be of the type string, null returned",
Where is my fault? Using Symfony 4.0.
The getter getLat has the return type hint string, which means only actual string values (that also means: no null values!) as return values are accepted.
You didn't show the code where you actually work with the entity, but it basically comes down to the default value of every property in an object being null if not defined differently.
Look at this example:
$address = new Address();
// the following lines will produce an error in your example
// because your return type hint doesn't allow null values
$address->getId(); // returns null
$address->getStreet(); // returns null
$address->getLat(); // returns null
$address->setLat("4.56789");
$address->getLat(); // returns "4.56789"
Note regarding Doctrine:
If the values in the database are set correctly, you won't run into this problem after Doctrine populated the entity (e.g. via $address = $addressRepo->find(123);). It should only happen, when you create a new entity yourself and then try to use the getter methods.
Possible solutions:
1.) Allow null values as return values. Prepend your return type hints with a question mark, like this:
/**
* #return string|null
*/
public function getLat(): ?string
{
return $this->lat;
}
But if you do this, your code must be ready to handle null values from these methods!
2.) Define default values with the correct data type in your object:
/**
* #var string
*
* #ORM\Column(name="lat", type="decimal", precision=10, scale=8, nullable=false)
*/
private $lat = "";
Your code must be ready to handle empty strings as return values then! Alternativly you can also define the default values in a constructor method.
3.) Require these properties to be available by making them parameters of your constructor:
public function __constructor(string $lat, string $lng /*, add the other required properties */) {
$this->lat = $lat;
$this->lng = $lng;
// ... additional properties here ...
}
In that case you must provide the values when you create the object with new Address(/* parameters go here */);.
Symfony 5:
public function getSomething(): ?string
{
return $this->something;
}
public function setSomething(string $something): self
{
$this->something= $something;
return $this;
}
just remove string from (string $something) like this and it should work, it does for me
public function getSomething(): ?string
{
return $this->something;
}
public function setSomething($something): self
{
$this->something= $something;
return $this;
}
I have a manyToMany relation beetween "Lot" and "BailProprietaire"
When i get an entity "BailProprietaire", i see the entities "lot" linked
But when i get an entity "Lot", i don't see entities "BailProprietaire" linked
In lot.orm.yml, i have :
AppBundle\Entity\Lot:
type: entity
repositoryClass: AppBundle\Repository\LotRepository
table: lot
....
....
manyToMany:
bauxProprietaire:
targetEntity: BailProprietaire
mappedBy: lots
In bailProprietaire.orm.yml, i have :
AppBundle\Entity\BailProprietaire:
type: entity
table: bail_proprietaire
repositoryClass: AppBundle\Repository\BailProprietaireRepository
....
....
manyToMany:
lots:
targetEntity: Lot
inversedBy: bauxProprietaire
fetch: LAZY
joinTable:
name: bail_proprietaire_lots
joinColumns:
bail_id:
referencedColumnName: id
inverseJoinColumns:
lot_id:
referencedColumnName: id
lifecycleCallbacks: { }
do you see something i miss ?
thanks
EDIT : Add php entity code
Lot.php
class Lot
{
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $bauxProprietaire;
/**
* Constructor
*/
public function __construct()
{
$this->bauxProprietaire = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add bauxProprietaire
*
* #param \AppBundle\Entity\BailProprietaire $bauxProprietaire
*
* #return Lot
*/
public function addBauxProprietaire(\AppBundle\Entity\BailProprietaire $bauxProprietaire)
{
$this->bauxProprietaire[] = $bauxProprietaire;
return $this;
}
/**
* Remove bauxProprietaire
*
* #param \AppBundle\Entity\BailProprietaire $bauxProprietaire
*/
public function removeBauxProprietaire(\AppBundle\Entity\BailProprietaire $bauxProprietaire)
{
$this->bauxProprietaire->removeElement($bauxProprietaire);
}
/**
* Get bauxProprietaire
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBauxProprietaire()
{
return $this->bauxProprietaire;
}
}
BailProprietaire.php
class BailProprietaire
{
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $lots;
/**
* Constructor
*/
public function __construct()
{
$this->lots = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add lot
*
* #param \AppBundle\Entity\Lot $lot
*
* #return BailProprietaire
*/
public function addLot(\AppBundle\Entity\Lot $lot)
{
$this->lots[] = $lot;
return $this;
}
/**
* Remove lot
*
* #param \AppBundle\Entity\Lot $lot
*/
public function removeLot(\AppBundle\Entity\Lot $lot)
{
$this->lots->removeElement($lot);
}
/**
* Get lots
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLots()
{
return $this->lots;
}
}
EDIT 2 : in fact, it works but not with the listener
in fact i see the entities "BailProprietaire" when i get a "lot" but when i flush data, i have a listener. In this listener, i call a virtual propertie of "Lot.php" where i have :
if (!empty($this->bauxProprietaire)) {
....
} else {
....
}
but $this->bauxProprietaire is always empty
Ok, i found the problem.
When i do $this->bauxProprietaire, i have a "Doctrine\ORM\PersistentCollection" but when i look the collection in this object, there is 0 element
but if i do $this->bauxProprietaire->toArray(), i see my relation
I don't understand why but it works
I'll simplifly my code, I have te next:
Doctor entity:
use ...\...\Entity\Paciente;
class Doctor extends Usuario {
public function __construct() {
...
$this->pacientes = new ArrayCollection();
...
}
/**
* Número de colegiado - numColegiado
*
* #var string
*
* #ORM\Column(name="numColegiado", type="string", length=255, unique=true)
*/
protected $numColegiado;
/**
* #ORM\OneToMany(targetEntity="Paciente", mappedBy="doctor")
* #var \Doctrine\Common\Collections\ArrayCollection
*/
private $pacientes;
...
}
Paciente entity:
use \...\...\Entity\Doctor;
...
class Paciente extends Usuario {
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Doctor", inversedBy="pacientes")
* #ORM\JoinColumn(name="doctorNum", referencedColumnName="numColegiado", nullable=TRUE)
*
* #var type
*/
protected $doctor;
...
/**
* Set doctor
*
* #param Doctor $doctor
* #return Paciente
*/
public function setDoctor(Doctor $doctor = null)
{
$this->doctor = $doctor;
return $this;
}
/**
* Get doctor
*
* #return Doctor
*/
public function getDoctor()
{
return $this->doctor;
}
}
Ok, the matter is, when I execute that code (of course there is a relationship created and this object exists in the database):
\Doctrine\Common\Util\Debug::dump($paciente->getDoctor());
It prints that follows:
object(stdClass)#804 (28) { ["__CLASS__"]=> string(34) "Knoid\CorcheckBundle\Entity\Doctor" ["__IS_PROXY__"]=> bool(true) ["__PROXY_INITIALIZED__"]=> bool(false) ["id"]=> NULL ["numColegiado"]=> NULL ["pacientes"]=> NULL ["nombre"]=> NULL ["apellidos"]=> NULL ["dni"]=> NULL ["tipo"]=> NULL ["username"]=> NULL ["usernameCanonical"]=> NULL ["email"]=> NULL ["emailCanonical"]=> NULL ["enabled"]=> NULL ["salt"]=> NULL ["password"]=> NULL ["plainPassword"]=> NULL ["lastLogin"]=> NULL ["confirmationToken"]=> NULL ["passwordRequestedAt"]=> NULL ["groups"]=> NULL ["locked"]=> NULL ["expired"]=> NULL ["expiresAt"]=> NULL ["roles"]=> NULL ["credentialsExpired"]=> NULL ["credentialsExpireAt"]=> NULL }
As you can see, all the atributes of the "doctor" object are null, the object exists but it's empty, in my DB this object exists and it isn't empty.
Any idea of what's happening ?
This is because the proxy object is not initialised yet. One way to initialise it, is by querying the object e.g. $doctor->getId(). If you dump the object after that, you'll see that all the attributes are 'visible'
The answer of Thomas K worked for me in my own Bundle. If I translate what I did :
$myPaciente = $em->getRepository('MyBundle:Paciente')->findOneBy(array('numColegiado' => $value));
I add $myPaciente->getDoctor()->getName();
Then the initialisation was done and I could dump $myPaciente with all the information about the doctor related to it.
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.