I'm using api-platform and I have a Book entity that has a ManyToOne relation to a Writer.
All writers are already persisted in the database, so I'd like to be able to create Books with a POST request containing the writer it is bound to.
But it keeps trying to persist a new writer.
How can I achieve that ?
Edit:
Books
/**
*
* #ORM\Entity(repositoryClass="App\Repository\BooksRepository")
* #ApiResource(
* attributes={
* "normalization_context"={"groups"={"read"}}
* }
*
* )
*/
class Books
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Property", inversedBy="beans")
* #ORM\JoinColumn(nullable=false)
* #Groups({"read"})
*/
private $property;
public function getProperty(): ?Property
{
return $this->property;
}
public function setProperty(?Property $property): self
{
$this->property = $property;
return $this;
}
}
Writers (also called Property)
/**
* #ORM\Entity(repositoryClass="App\Repository\PropertyRepository")
*/
class Property
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"read"})
*/
private $id;
/**
* #ORM\Column(type="string", length=30)
* #Groups({"read"})
*/
private $type;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Books", mappedBy="property", orphanRemoval=true)
* #Groups({"read"})
*/
private $books;
public function __construct()
{
$this->books = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
/**
* #return Collection|Books[]
*/
public function getBooks(): Collection
{
return $this->books;
}
public function addBook(Books $book): self
{
if (!$this->books->contains($book)) {
$this->books[] = $book;
$book->setProperty($this);
}
return $this;
}
public function removeBook(Books $book): self
{
if ($this->books->contains($book)) {
$this->books->removeElement($book);
// set the owning side to null (unless already changed)
if ($book->getProperty() === $this) {
$book->setProperty(null);
}
}
return $this;
}
}
The following request should do the trick:
POST /books
{
"property": "/writers/1"
}
Related
During a production cache clear I have this message : The type hint of parameter "imageFile" in method "setImageFile" in class "App\Entity\Evenement" is invalid. I follow the instruction of the VichUploaderBundle's documentation on github "basic usage".
Thanks for your help !
below the code of the entity :
<?php
namespace App\Entity;
use App\Repository\EvenementRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\component\HttpFoundation\File\File;
use Symfony\component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass=EvenementRepository::class)
* #vich\Uploadable
*/
class Evenement
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*
*/
private $titre;
/**
* #ORM\Column(type="string", length=2000, nullable=true)
*/
private $description;
/**
* #ORM\Column(type="string", length=500, nullable=true)
* #Assert\Url()
*/
private $visuel;
/**
* #Vich\UploadableField(mapping="evenement", fileNameProperty="imageName")
* #var File|null
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #var string|null
*/
private $imageName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTimeInterface|null
*/
private $updatedAt;
/**
* #ORM\Column(type="string", length=500, nullable=true)
*/
private $tarifs;
/**
* #ORM\Column(type="datetime")
*/
private $date;
/**
* #ORM\ManyToMany(targetEntity=Film::class, inversedBy="evenements")
*/
private $films;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dateFin;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $video;
public function __construct()
{
$this->films = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getVisuel(): ?string
{
return $this->visuel;
}
public function setVisuel(?string $visuel): self
{
$this->visuel = $visuel;
return $this;
}
public function getTarifs(): ?string
{
return $this->tarifs;
}
public function setTarifs(?string $tarifs): self
{
$this->tarifs = $tarifs;
return $this;
}
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(\DateTimeInterface $date): self
{
$this->date = $date;
return $this;
}
/**
* #return Collection|Film[]
*/
public function getFilms(): Collection
{
return $this->films;
}
public function addFilm(Film $film): self
{
if (!$this->films->contains($film)) {
$this->films[] = $film;
}
return $this;
}
public function removeFilm(Film $film): self
{
$this->films->removeElement($film);
return $this;
}
public function getDateFin(): ?\DateTimeInterface
{
return $this->dateFin;
}
public function setDateFin(?\DateTimeInterface $dateFin): self
{
$this->dateFin = $dateFin;
return $this;
}
public function getVideo(): ?string
{
return $this->video;
}
public function setVideo(?string $video): self
{
$this->video = $video;
return $this;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile
*/
public function setImageFile(?File $imageFile = null): void
{
$this->imageFile = $imageFile;
if (null !== $imageFile) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
public function setImageName(?string $imageName): void
{
$this->imageName = $imageName;
}
public function getImageName(): ?string
{
return $this->imageName;
}
}
Please set your fields according to this
Note: Don't forgot to update your database
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Entity\File as EmbeddedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Assert\File(
* maxSize="51200k",
* mimeTypes = {
* "image/jpeg",
* "image/gif",
* "image/png",
* }
* )
* #Vich\UploadableField(
* mapping="evenement_image",
* fileNameProperty="imageFile.name",
* size="imageFile.size",
* originalName="imageFile.originalName",
* mimeType="imageFile.mimeType"
* )
*
* #var File|null
*/
protected $image;
/**
* #ORM\Embedded(class="Vich\UploaderBundle\Entity\File")
*
* #var EmbeddedFile
*/
protected $imageFile;
public function __construct()
{
$this->imageFile = new EmbeddedFile();
}
public function setImage(?File $image = null): void
{
$this->image = $image;
if (null !== $image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new DateTimeImmutable();
}
}
public function getImage(): ?File
{
return $this->image;
}
public function getImageFile(): ?EmbeddedFile
{
return $this->imageFile;
}
public function setImageFile(EmbeddedFile $imageFile): self
{
$this->imageFile = $imageFile;
return $this;
}
I have an intermediate table that acts as a pivot between two others: user, punto_suministro and table pivot user_punto_suministro:
How to fetch data from table user to table punto_suministro?
Entity User:
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
.....
/**
* #ORM\OneToMany(targetEntity=UserPuntoSuministro::class, mappedBy="user")
*/
private $userPuntoSuministros;
/**
* #throws \Exception
*/
public function __construct()
{
$this->puntoSuministros = new ArrayCollection();
$this->userPuntoSuministros = new ArrayCollection();
}
/**
* #return Collection|UserPuntoSuministro[]
*/
public function getUserPuntoSuministros(): Collection
{
return $this->userPuntoSuministros;
}
public function addUserPuntoSuministro(UserPuntoSuministro $userPuntoSuministro): self
{
if (!$this->userPuntoSuministros->contains($userPuntoSuministro)) {
$this->userPuntoSuministros[] = $userPuntoSuministro;
$userPuntoSuministro->setUser($this);
}
return $this;
}
public function removeUserPuntoSuministro(UserPuntoSuministro $userPuntoSuministro): self
{
if ($this->userPuntoSuministros->contains($userPuntoSuministro)) {
$this->userPuntoSuministros->removeElement($userPuntoSuministro);
// set the owning side to null (unless already changed)
if ($userPuntoSuministro->getUser() === $this) {
$userPuntoSuministro->setUser(null);
}
}
return $this;
}
Entity PuntoSuministro:
/**
* #ORM\Entity(repositoryClass=PuntoSuministroRepository::class)
*/
class PuntoSuministro
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
...
/**
* #ORM\OneToMany(targetEntity=UserPuntoSuministro::class, mappedBy="punto_suministro")
*/
private $userPuntoSuministros;
public function __construct()
{
$this->userPuntoSuministros = new ArrayCollection();
}
/**
* #return Collection|UserPuntoSuministro[]
*/
public function getUserPuntoSuministros(): Collection
{
return $this->userPuntoSuministros;
}
public function addUserPuntoSuministro(UserPuntoSuministro $userPuntoSuministro): self
{
if (!$this->userPuntoSuministros->contains($userPuntoSuministro)) {
$this->userPuntoSuministros[] = $userPuntoSuministro;
$userPuntoSuministro->setPuntoSuministro($this);
}
return $this;
}
public function removeUserPuntoSuministro(UserPuntoSuministro $userPuntoSuministro): self
{
if ($this->userPuntoSuministros->contains($userPuntoSuministro)) {
$this->userPuntoSuministros->removeElement($userPuntoSuministro);
// set the owning side to null (unless already changed)
if ($userPuntoSuministro->getPuntoSuministro() === $this) {
$userPuntoSuministro->setPuntoSuministro(null);
}
}
return $this;
}
Entity UserPuntoSuministro (table pivot):
/**
* #ORM\Entity(repositoryClass=UserPuntoSuministroRepository::class)
*/
class UserPuntoSuministro
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="userPuntoSuministros")
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity=PuntoSuministro::class, inversedBy="userPuntoSuministros")
*/
private $punto_suministro;
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getPuntoSuministro(): ?PuntoSuministro
{
return $this->punto_suministro;
}
public function setPuntoSuministro(?PuntoSuministro $punto_suministro): self
{
$this->punto_suministro = $punto_suministro;
return $this;
}
I try and access as follows:
$user = $userRepository->find($this->security->getUser());
$pivote = $user->getUserPuntoSuministros();
but from here I don't know how to recover the punto_suministro of a user to show it on twig.
Thanks in advance.
In simple case you could iterate over $user->getUserPuntoSuministros() and fetch concrete punto_suministro's
$user = $userRepository->find($this->security->getUser());
$puntoSuministros = []; // contains PuntoSuministro's of User
foreach ($user->getUserPuntoSuministros() as $userPuntoSuministro) {
$puntoSuministros[] = $userPuntoSuministro->getPuntoSuministro();
}
I have an entity Voucher that contain a custom operation name add_voucher:
<?php
/**
* #ApiResource(
* collectionOperations={
* "add_voucher"={
* "access_control"="is_granted('ROLE_COMMERCIAL')",
* "method"="POST",
* "path"="/vouchers/add-new",
* "controller"=AddVoucherAction::class,
* "denormalization_context"={
* "groups"={"add_new_voucher"}
* },
* "validation_groups"={"Default", "add_voucher_validation"}
* },
* }
* )
* #ORM\Entity(repositoryClass="App\Repository\VoucherRepository", repositoryClass=VoucherRepository::class)
*/
class Voucher
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #Groups("add_new_voucher")
* #ORM\Column(type="string", length=255, unique=true)
*/
private $code;
/**
* #Groups("add_new_voucher")
* #ORM\Column(type="integer")
*/
private $discount;
/**
* #Groups("add_new_voucher")
* #ORM\Column(type="datetime")
*/
private $starts_at;
public function getDiscount()
{
return $this->discount;
}
public function setDiscount($discount): void
{
$this->discount = $discount;
}
public function getId(): ?int
{
return $this->id;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): self
{
$this->code = $code;
return $this;
}
public function getStartsAt(): ?\DateTimeInterface
{
return $this->starts_at;
}
public function setStartsAt(\DateTimeInterface $starts_at): self
{
$this->starts_at = $starts_at;
return $this;
}
}
I added the denormalization group to code,discount,starts_at, I Later to validate this columns in operations to do so I need to add it first in the denormalization context but in the swagger it show only
the code and discount properties
It is because of the spelling combination of your $starts_at property and getStartsAt() getter. Basically, Symfony serializer use yours getters to access private properties.
Just replace either your property by $starstAt or add an underscore to your getter.
Take a look at this;
I have two Entities
User
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="first_name", type="text", nullable=true)
*/
protected $firstName;
/**
* #ORM\Column(name="last_name", type="text", nullable=true)
*/
protected $lastName;
/**
* #ORM\Column(type="bigint", nullable=true)
*/
protected $phone;
/**
* #ORM\Column(name="birth_date", type="date", nullable=true)
*/
protected $birthDate;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $gender;
/**
* #ORM\Column(name="location_country", type="text", nullable=true)
*/
protected $locationCountry;
/**
* #ORM\Column(name="location_city", type="text", nullable=true)
*/
protected $locationCity;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $avatar;
/**
* #ORM\Column(name="wall_image", type="text", nullable=true)
*/
protected $wallImage;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $about;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="user")
*/
protected $followers;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="follower")
*/
protected $followings;
/**
* Is followed. Used when checking is followed by another user.
*/
protected $isFollowed = false;
/**
* #ORM\OneToMany(targetEntity="Photo", mappedBy="user")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $photos;
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getPhone()
{
return $this->phone;
}
public function getBirthDate()
{
return $this->birthDate;
}
public function getGender()
{
return $this->gender;
}
public function getLocationCountry()
{
return $this->locationCountry;
}
public function getLocationCity()
{
return $this->locationCity;
}
public function getAvatar()
{
return $this->avatar;
}
public function getAvatarImage()
{
return $this->getAvatarPath().$this->avatar;
}
public function getWallImage()
{
return $this->wallImage;
}
public function getAbout()
{
return $this->about;
}
public function getAvatarPath()
{
return '/web/uploads/avatars/'.$this->id.'/';
}
public function getWallImagePath()
{
return '/web/uploads/wall/'.$this->id.'/';
}
public function getFollowers()
{
return $this->followers;
}
public function getFollowings()
{
return $this->followings;
}
public function getFollowersCount()
{
//print_r($this->followers->toArray());
}
public function getPhotos()
{
return $this->photos;
}
public function isFollowed()
{
return $this->isFollowed;
}
public function setFirstName($value)
{
$this->firstName = $value;
}
public function setLastName($value)
{
$this->lastName = $value;
}
public function setPhone($value)
{
$this->phone = $value;
}
public function setBirthDate($value)
{
$this->birthDate = $value;
}
public function setGender($value)
{
$this->gender = $value;
}
public function setLocationCountry($value)
{
$this->locationCountry = $value;
}
public function setLocationCity($value)
{
$this->locationCity = $value;
}
public function setAvatar($path)
{
$this->avatar = $path;
}
public function setWallImage($path)
{
$this->wallImage = $path;
}
public function setAbout($about)
{
$this->about = $about;
}
public function setFollowed($isFollowed)
{
$this->isFollowed = $isFollowed;
}
}
Photo
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="photos")
*/
class Photo
{
const
CATEGORY_PHOTOGRAPHY = 1,
CATEGORY_PAINTING = 2,
CATEGORY_3D = 3;
/*
* Flow photos limit
*/
const FLOW_PHOTOS_LIMIT = 15;
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="photos")
*/
protected $user;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $title;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* #ORM\Column(type="text")
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="PhotoCategory")
*/
protected $category;
/**
* #ORM\Column(name="creation_date", type="datetime")
*/
protected $creationDate;
/**
* #ORM\Column(name="edit_date", type="datetime", nullable=true)
*/
protected $editDate;
/**
* #ORM\Column(name="is_moderated", type="boolean")
*/
protected $isModerated = false;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
protected $isActive = true;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="photo")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $comments;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param User $user
*
* #return Photo
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User $user
*/
public function getUser()
{
return $this->user;
}
/**
* Get category
*
* #return Category $category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set title
*
* #param string $title
*
* #return Photo
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Get editDate
*
* #return \DateTime
*/
public function getEditDate()
{
return $this->editDate;
}
/**
* Get is active
*
* #return integer
*/
public function isActive()
{
return $this->isActive;
}
/**
* Get is moderated
*
* #return integer
*/
public function isModerated()
{
return $this->isModerated;
}
/*
* Get image
*
* #return string
*/
public function getImage()
{
return $this->getWebDirectory().$this->getName();
}
/*
* Get image directory
*
* #return string
*/
public function getDirectory()
{
return __DIR__.'/../../../web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get image web directory
*
* #return string
*/
public function getWebDirectory()
{
return '/web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get comments
*/
public function getComments()
{
return $this->comments;
}
/**
* Set description
*
* #param string $description
*
* #return Photo
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set name
*
* #param string $name
*
* #return Photo
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
*/
public function setCreationDate(\DateTime $creationDate)
{
$this->creationDate = $creationDate;
}
/**
* Set editDate
*
* #param \DateTime $editDate
*/
public function setEditDate(\DateTime $editDate)
{
$this->editDate = $editDate;
}
/**
* Set active
*/
public function setActive($active)
{
$this->isActive = $active;
}
/**
* Set category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* Set moderated
*/
public function setModerated($moderated)
{
$this->isModerated = $moderated;
}
}
As you see, i have isActive in Photo, which is telling is photo deleted or not. So, i get all users photos via User->getPhotos() which is one-to-many. But it return all users photos. How should be done, so it returns all photos which have isActive = true?
thank you
you can try the filter method to query inside entities
$user->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
There are a number of ways you can do this.
Cosmin provided one for you, which will result in Doctrine loading each photo, and then PHP code checking to see whether or not it is active. This will work in the most number of situations, but will potentially be slow inefficient.
Yet another solution, is to use "criteria":
$exp = new \Doctrine\ORM\Query\Expr();
$activePhotos = $user->getPhotos()->matching(
new \Doctrine\Common\Collections\Criteria(
$exp->eq('active', true)
)
);
This will do something similar to the filter that Cosmin suggested, but allow for Doctrine to filter at the database level.
You can create a method inside the User entity, using the code of #Cosmin Ordean :) Something like this
public function getActivePhotos() {
return $this->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
}
I serialize some values when I send to DB, now I need to unserialize them in order to iterate over them. In my entity I have this:
public function getValuesText() {
return $this->values_text;
}
and then in the template I show as:
{{ element.getValuesText }}
But I get this raw result:
a:3:{i:1;s:7:"Value 1";i:2;s:7:"Value 2";i:3;s:7:"Value 3";}
And I don't know how to iterate over it to get key, values, what is failing?
UPDATE: Include mapping information
Here is:
<?php
namespace ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use ProductBundle\DBAL\Types\StatusType;
use ProductBundle\DBAL\Types\FieldType;
use Fresh\Bundle\DoctrineEnumBundle\Validator\Constraints as DoctrineAssert;
/**
* #ORM\Entity
* #ORM\Table(name="product_detail")
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class ProductDetail {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="ProductDetail")
* #ORM\JoinColumn(name="parent", referencedColumnName="id")
*/
protected $parent;
/**
* #ORM\Column(type="string", length=255)
*/
protected $description;
/**
* #ORM\Column(type="string", length=255)
*/
protected $label;
/**
* #var string $field_type
* #DoctrineAssert\Enum(entity="ProductBundle\DBAL\Types\FieldType")
* #ORM\Column(name="field_type", type="FieldType", nullable=false)
*/
protected $field_type;
/**
* #ORM\Column(name="values_text", type="array")
*/
protected $values_text;
/**
* #ORM\Column(type="string", length=255)
*/
protected $measure_unit;
/**
* #var string $status
* #DoctrineAssert\Enum(entity="ProductBundle\DBAL\Types\StatusType")
* #ORM\Column(name="status", type="StatusType", nullable=false)
*/
protected $status;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="created", type="datetime")
*/
protected $created;
/**
* #Gedmo\Timestampable(on="update")
* #ORM\Column(name="modified", type="datetime")
*/
protected $modified;
/**
* #ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
protected $deletedAt;
/**
* #ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", inversedBy="pd_category", cascade={"persist"})
* #ORM\JoinTable(name="product_detail_has_category",
* joinColumns={#ORM\JoinColumn(name="detail", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category", referencedColumnName="id")}
* )
*/
protected $category;
/**
* #ORM\ManyToMany(targetEntity="ProductBundle\Entity\DetailGroup", inversedBy="productDetail", cascade={"persist"})
* #ORM\JoinTable(name="detail_group_has_product_detail",
* joinColumns={#ORM\JoinColumn(name="detail", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="kgroup", referencedColumnName="id")}
* )
*/
protected $detail_group;
/**
* #ORM\Column(name="to_product", type="boolean")
*/
protected $to_product;
public function __construct() {
$this->detail_group = new \Doctrine\Common\Collections\ArrayCollection();
$this->category = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function setParent(ProductDetail $parent = null) {
$this->parent = $parent;
}
public function getParent() {
return $this->parent;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setLabel($label) {
$this->label = $label;
}
public function getLabel() {
return $this->label;
}
public function setFieldType($field_type) {
$this->field_type = $field_type;
}
public function getFieldType() {
return $this->field_type;
}
public function setValuesText($values_text) {
$this->values_text = $values_text;
}
public function getValuesText() {
return $this->values_text;
}
public function setMeasureUnit($measure_unit) {
$this->measure_unit = $measure_unit;
}
public function getMeasureUnit() {
return $this->measure_unit;
}
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setCreated($param) {
$this->created = $param;
return true;
}
public function getCreated() {
return $this->created;
}
public function setModified($param) {
$this->modified = $param;
return true;
}
public function getModified() {
return $this->modified;
}
public function setCategory(\CategoryBundle\Entity\Category $category) {
$this->category[] = $category;
}
public function getCategory() {
return $this->category;
}
public function setDetailGroup(\ProductBundle\Entity\DetailGroup $detailGroup) {
$this->detail_group[] = $detailGroup;
}
public function getDetailGroup() {
return $this->detail_group;
}
public function getDeletedAt() {
return $this->deletedAt;
}
public function setDeletedAt($deletedAt) {
$this->deletedAt = $deletedAt;
}
public function setToProduct($to_product) {
$this->to_product = $to_product;
}
public function getToProduct() {
return $this->to_product;
}
}
Ok, after read and check my code I realize where the problem was:
Doctrine DBAL takes care for serialize/unserialize by using type="array" check here for more info
I made a mistake when I insert values since I was doing a unwanted serialize since as I said before Doctrine take care of this. See below:
Incorrect:
$entity->setValuesText(serialize($form->get('values_text')->getData()));
Correct:
$entity->setValuesText($form->get('values_text')->getData());
That's all, hope is helpful for someone else
Doctrine 2 DBAL ArrayType doesn't check for an array and serialize every type of parameter.
Control your database, that value should be a serialized string starting with s:
Ref: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Types/ArrayType.php