option orphanRemoval is ignored - php

I try to make a form for an entity called Product with an embedded form from an entity Barcode. When I edit an existing product and remove a barcode, it is still in the database with a product_id set to NULL. How can I do to remove it completely ?
My Barcode Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\BarcodeRepository")
*/
class Barcode
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $code;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Product", inversedBy="barcodes")
* #ORM\JoinColumn(nullable=false)
*/
private $product;
public function __construct(Product $product = null)
{
$this->product = $product;
}
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 getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
return $this;
}
}
My Product Entity :
<?php
namespace App\Entity;
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\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #UniqueEntity("slug")
*/
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\Regex(pattern="/\.(svg|png)$/")
*/
protected $picture;
/**
* #ORM\Column(type="boolean")
*/
protected $is_activated;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $comments;
/**
* #ORM\Column(type="datetime")
*/
protected $created_at;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Barcode", mappedBy="product", orphanRemoval=true, cascade={"all"})
*/
protected $barcodes;
public function __construct()
{
$this->allergens = new ArrayCollection();
$this->barcodes = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getPicture(): ?string
{
return $this->picture;
}
public function setPicture(string $picture): self
{
$this->picture = $picture;
return $this;
}
public function getIsActivated(): ?bool
{
return $this->is_activated;
}
public function setIsActivated(bool $is_activated): self
{
$this->is_activated = $is_activated;
return $this;
}
public function getComments(): ?string
{
return $this->comments;
}
public function setComments(?string $comments): self
{
$this->comments = $comments;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
/**
* #return Collection|Barcode[]|null
*/
public function getBarcodes(): ?Collection
{
return $this->barcodes;
}
public function addBarcode(Barcode $barcode): self
{
if (!$this->barcodes->contains($barcode)) {
$this->barcodes[] = $barcode;
$barcode->setProduct($this);
}
return $this;
}
public function removeBarcode(Barcode $barcode): self
{
if ($this->barcodes->contains($barcode)) {
$this->barcodes->removeElement($barcode);
// set the owning side to null (unless already changed)
if ($barcode->getProduct() === $this) {
$barcode->setProduct(null);
}
}
return $this;
}
}
and my ProductType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('slug')
->add('picture')
->add('barcodes', CollectionType::class, [
'entry_type' => BarcodeType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false
])
->add('is_activated')
->add('comments')
;
}

Related

EntityType form returns a String instead of object

I have a user entity that has a many-to-many relationship with another entity Roles.
I have a form that allows me to create a new user and for that, I use an EntityType for the manyToMany relationship 'roles'.
Here is my form
$builder
->add('username',null,['label' => 'Email'])
->add('password',null,['label'=>'Password'])
->add('roles',EntityType::class, [
'multiple' => true,
'class' => Role::class,
'choice_label' => 'role_name',
]
)
;
Everything works fine but when I submit the form I got this error:
Expected argument of type "App\Entity\Role", "string" given at
property path "roles".
EDIT:
here is my User entity :
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity=Role::class, inversedBy="users")
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getRoles()
{
return ['ROLE_ADMIN'];
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function addRole(Role $role): self
{
if (!$this->roles->contains($role)) {
$this->roles[] = $role;
$role->addUser($this);
}
return $this;
}
public function removeRole(Role $role): self
{
if ($this->roles->contains($role)) {
$this->roles->removeElement($role);
$role->removeUser($this);
}
return $this;
}
}
Here is my Role entity :
<?php
namespace App\Entity;
use App\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=RoleRepository::class)
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $role_name;
/**
* #ORM\ManyToMany(targetEntity=User::class, mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoleName(): ?string
{
return $this->role_name;
}
public function setRoleName(string $role_name): self
{
$this->role_name = $role_name;
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
}
return $this;
}
}
I guess the problem is here
public function getRoles()
{
return ['ROLE_ADMIN'];
}
you should return an array or Role entity not string, it should be something like this
public function getRoles()
{
return $this->roles;
}
what if i'm using ArrayCollection in User entity?
/**
* #var Collection|Role[]
* #ORM\ManyToMany(targetEntity="App\Entity\Role")
* #ORM\JoinTable(
* name="user_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles;
}

Symfony cmd error "The target-entity..cannot be found in.."

I'm starting with Symfony Framework and I am trying to make ManyToMany relationship.
But when I try this commandline
php bin/console doctrine:schema:update
I am getting this error:
The target-entity C:\xampp\htdocs\symfony-tp\src\Entity\Competetence cannot be found in 'App\Entity\Stagiaire#competencies'.
Stagiaire.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\StagiaireRepository")
*/
class Stagiaire
{
/**
* #ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
*/
private $competencies;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\Column(type="string", length=50)
*/
private $name;
/**
* #ORM\Column(type="integer")
*/
private $phone;
/**
* #ORM\Column(type="datetime")
*/
private $birthday;
/**
* #var \Datetime
*/
private $date;
public function __construct()
{
$this->date = new \Datetime();
$this->competencies = new ArrayCollection();
}
public function addCompetence(Competence $competence)
{
$this->$competence[] = $competence;
return $this;
}
public function removeCompetence(Competence $competence)
{
$this->competencies->removeElement($competence);
}
public function getCompetencies()
{
return $this->competencies;
}
public function getId(): ?int
{
return $this->id;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getPhone(): ?int
{
return $this->phone;
}
public function setPhone(int $phone): self
{
$this->phone = $phone;
return $this;
}
public function getBirthday(): ?\DateTimeInterface
{
return $this->birthday;
}
public function setBirthday(\DateTimeInterface $birthday): self
{
$this->birthday = $birthday;
return $this;
}
}
Competence.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\CompetenceRepository")
*/
class Competence
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=50)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
Thanks for your help !
In Stagiaire::$competencies annotation you need to provide Competence's Fully-Qualified Class Name instead of file path on your computer, and that would be App\Entity\Competence
So this:
/**
* #ORM\ManyToMany(targetEntity="C:\xampp\htdocs\symfony-tp\src\Entity\Competetence",cascade={"persist"})
*/
private $competencies;
Becomes:
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Competence",cascade={"persist"})
*/
private $competencies;

Doctrine ManyToOne Relation not finding data with findBy method

I have a Article table that is allowed to have many comments.
And when i use findBy it does not find anything for that Article.
Here is my show Action.
$comments = $commentRepository->findBy(['article' => $article]);
dump($comments);die;
which just outputs-.
ArticleController.php on line 52:
[]
When i do findAll however i get 20 Results which look like this
$allComments = $commentRepository->findAll();
dump($allComments);die;
0 => Comment^ {#881 ▼
-id: 1
-authorName: "Author name here"
-content: "Here is the comment content"
-article: Article^ {#809 ▼
+__isInitialized__: false
-id: 117
-title: null
-slug: null
-content: null
-publishedAt: null
-author: null
-heartCount: 0
-imageFilename: null
-createdAt: null
-updatedAt: null
-comments: null
…2
}
Here is the complete showAction method
/**
* #Route("/news/{article}",
* name="article_show")
*
* #param Article $article
* #param SlackClient $slack
* #param EntityManagerInterface $entityManager
* #param CommentRepository $commentRepository
* #return \Symfony\Component\HttpFoundation\Response
* #throws \Http\Client\Exception
* #throws \Nexy\Slack\Exception\SlackApiException
*/
public function show( $article,
SlackClient $slack,
EntityManagerInterface $entityManager,
CommentRepository $commentRepository
)
{
$allComments = $commentRepository->findAll();
$comments = $commentRepository->findBy(['article' => $article]);
dump($allComments);die;
$repository = $entityManager->getRepository(Article::class);
/**
* #var Article $article
*/
$articleResult = $repository->findOneBy(['slug' => $article]);
if (!$articleResult) {
throw $this->createNotFoundException('No ' . $article . ' found');
}
Not sure if needed but here is my Article and Comment Entitiy just to make sure i have verything here.
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
*/
class Article
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $title;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(type="string", length=100, unique=true)
*/
private $slug;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $content;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $publishedAt;
/**
* #ORM\Column(type="string", length=255)
*/
private $author;
/**
* #ORM\Column(type="integer")
*/
private $heartCount = 0;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $imageFilename;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="create")
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
* #Gedmo\Timestampable(on="update")
*/
private $updatedAt;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="article")
*/
private $comments;
public function __construct()
{
$this->comments = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(?string $content): self
{
$this->content = $content;
return $this;
}
public function getPublishedAt(): ?\DateTimeInterface
{
return $this->publishedAt;
}
public function setPublishedAt(?\DateTimeInterface $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
public function getAuthor(): ?string
{
return $this->author;
}
public function setAuthor(string $author): self
{
$this->author = $author;
return $this;
}
public function getHeartCount(): ?int
{
return $this->heartCount;
}
public function setHeartCount(int $heartCount): self
{
$this->heartCount = $heartCount;
return $this;
}
public function getImageFilename(): ?string
{
return $this->imageFilename;
}
public function setImageFilename(?string $imageFilename): self
{
$this->imageFilename = $imageFilename;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* #return Collection|Comment[]
*/
public function getComments(): Collection
{
return $this->comments;
}
public function addComment(Comment $comment): self
{
if (!$this->comments->contains($comment)) {
$this->comments[] = $comment;
$comment->setArticle($this);
}
return $this;
}
public function removeComment(Comment $comment): self
{
if ($this->comments->contains($comment)) {
$this->comments->removeElement($comment);
// set the owning side to null (unless already changed)
if ($comment->getArticle() === $this) {
$comment->setArticle(null);
}
}
return $this;
}
}
and the Comments Entitiy.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
* #ORM\Entity(repositoryClass="App\Repository\CommentRepository")
*/
class Comment
{
use TimestampableEntity;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $authorName;
/**
* #ORM\Column(type="text")
*/
private $content;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="comments")
* #ORM\JoinColumn(nullable=false)
*/
private $article;
public function getId(): ?int
{
return $this->id;
}
public function getAuthorName(): ?string
{
return $this->authorName;
}
public function setAuthorName(string $authorName): self
{
$this->authorName = $authorName;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getArticle(): ?article
{
return $this->article;
}
public function setArticle(?article $article): self
{
$this->article = $article;
return $this;
}
}
Please let me know if you need any other information
The problem lies in showAction method.
You want to take a look at $article argument. Phpdoc says it will be instance of Article but it won't be.
Here:
$articleResult = $repository->findOneBy(['slug' => $article]);
You assume that $article contains string representing slug.
So you search for comments by article slug and comments don't contain this information. You want to fetch them by article id.

Problems with multiple upload images easyadmin

Hello I have several problems with the easyadmin multiple image uploads. Please help. Strangely I was having problems mostly with cakes and cakephotos. In easyadmin I add several images in Cakes, they get converted to array and stored in the db. After they get outputed when showed. Atleast that what I was planning to do...
Here is the Cakes.php entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Vich\UploaderBundle\Entity\File as EmbeddedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass="App\Repository\CakesRepository")
* #Vich\Uploadable
*/
class Cakes
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $CakeName;
/**
* #ORM\Column(type="integer")
*/
private $CakePrice;
/**
* #ORM\Column(type="string", length=255)
*/
private $Description;
/**
* #ORM\Column(type="json")
*/
private $CakeCategory = [];
/**
* #ORM\ManyToMany(targetEntity="Location", mappedBy="Cakes", cascade={"persist"})
*/
private $AvailableLocation = [];
/**
* #ORM\OneToMany(targetEntity="CakePhotos", mappedBy="Cake", cascade={"persist"})
*/
private $CakePhotos;
public function __construct()
{
$this->AvailableLocation = new ArrayCollection();
$this->CakePhotos = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getCakeName(): ?string
{
return $this->CakeName;
}
public function setCakeName(string $CakeName): self
{
$this->CakeName = $CakeName;
return $this;
}
public function getCakePrice(): ?int
{
return $this->CakePrice;
}
public function setCakePrice(int $CakePrice): self
{
$this->CakePrice = $CakePrice;
return $this;
}
public function getDescription(): ?string
{
return $this->Description;
}
public function setDescription(string $Description): self
{
$this->Description = $Description;
return $this;
}
public function getCakeCategory(): ?array
{
return $this->CakeCategory;
}
public function setCakeCategory(array $CakeCategory): self
{
$this->CakeCategory = $CakeCategory;
return $this;
}
/**
* #return Collection|Location[]
*/
public function getAvailableLocation(): Collection
{
return $this->AvailableLocation;
}
public function addAvailableLocation(Location $location): self
{
if (!$this->AvailableLocation->contains($location)) {
$this->AvailableLocation[] = $location;
$location->addCake($this);
}
return $this;
}
public function removeAvailableLocation(Location $location): self
{
if ($this->AvailableLocation->contains($location)) {
$this->AvailableLocation->removeElement($location);
$location->removeCake($this);
}
return $this;
}
/**
* #return Collection|CakePhoto[]
*/
public function getCakePhotos(): Collection
{
return $this->CakePhotos;
}
public function addCakePhoto(CakePhotos $CakePhotos): self
{
if (!$this->CakePhotos->contains($CakePhotos)) {
$this->CakePhoto[] = $CakePhotos;
$CakePhotos->setCake($this);
}
return $this;
}
public function removeCakePhoto(CakePhotos $CakePhotos): self
{
if ($this->CakePhotos->contains($CakePhotos)) {
$this->CakePhotos->removeElement($CakePhotos);
}
return $this;
}
public function getImageURL(): ?string
{
return $this->ImageURL;
}
public function setImageURL(string $ImageURL): self
{
$this->ImageURL = $ImageURL;
return $this;
}
}
Here is the CakePhotos.php entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity(repositoryClass="App\Repository\CakePhotosRepository")
* #Vich\Uploadable
*/
class CakePhotos
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $Image;
/**
* #Vich\UploadableField(mapping="cakephotos", fileNameProperty="Image")
*/
private $ImageFile;
/**
* #ORM\ManyToOne(targetEntity="Cakes", inversedBy="CakePhotos")
*/
private $Cake;
public function getId(): ?int
{
return $this->id;
}
public function getImage(): ?string
{
return $this->Image;
}
public function setImage(?string $Image)
{
$this->Image = $Image;
return $this;
}
public function getCake(): ?Cakes
{
return $this->Cake;
}
public function setCake(?Cake $cake): self
{
$this->Cake = $cake;
return $this;
}
public function __toString()
{
return $this->Image;
}
/**
* #return mixed
*/
public function getImageFile()
{
return $this->ImageFile;
}
/**
* #param mixed $imageFile
* #throws \Exception
*/
public function setImageFile(?File $ImageFile): void
{
$this->ImageFile = $ImageFile;
}
}
Here is my Form for converting
<?php
namespace App\Form;
use App\Entity\CakePhotos;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichFileType;
class ImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ImageFile', VichFileType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => CakePhotos::class,
]);
}
}
All around the code I have different problems such as:
Argument 1 passed to App\Entity\CakePhotos::setCake() must be an instance of App\Entity\Cake or null, instance of App\Entity\Cakes given, called in /home/kumaskano1/Desktop/Learning/Symfony/Shirin/src/Entity/Cakes.php
you can solve your problem by doing this
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ImageFile', VichFileType::class,array('data_class' =>null))
;
}

Error on "simple" CollectionType inclusion

I try to make a form for an entity called Product with an embedded form from an entity Barcode. When I try to go to the form to add one product, I have the message "Return value of App\Entity\Product::getBarcodes() must implement interface Doctrine\Common\Collections\Collection, null returned".
I say in __construct to initialize the barcodes to implement the Collection but still the same..
My Barcode Entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\BarcodeRepository")
*/
class Barcode
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $code;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Product", inversedBy="barcodes")
* #ORM\JoinColumn(nullable=false)
*/
private $product;
public function __construct(Product $product = null)
{
$this->product = $product;
}
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 getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
return $this;
}
}
My Product Entity :
<?php
namespace App\Entity;
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\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #UniqueEntity("slug")
*/
class Product
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #ORM\Column(type="string", length=255)
* #Assert\Regex(pattern="/\.(svg|png)$/")
*/
protected $picture;
/**
* #ORM\Column(type="boolean")
*/
protected $is_activated;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $comments;
/**
* #ORM\Column(type="datetime")
*/
protected $created_at;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Barcode", mappedBy="product", orphanRemoval=true, cascade={"all"})
*/
protected $barcodes;
public function __construct()
{
$this->allergens = new ArrayCollection();
$this->barcodes = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getPicture(): ?string
{
return $this->picture;
}
public function setPicture(string $picture): self
{
$this->picture = $picture;
return $this;
}
public function getIsActivated(): ?bool
{
return $this->is_activated;
}
public function setIsActivated(bool $is_activated): self
{
$this->is_activated = $is_activated;
return $this;
}
public function getComments(): ?string
{
return $this->comments;
}
public function setComments(?string $comments): self
{
$this->comments = $comments;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
/**
* #return Collection|Barcode[]
*/
public function getBarcodes(): Collection
{
return $this->barcodes;
}
public function addBarcode(Barcode $barcode): self
{
if (!$this->barcodes->contains($barcode)) {
$this->barcodes[] = $barcode;
$barcode->setProduct($this);
}
return $this;
}
public function removeBarcode(Barcode $barcode): self
{
if ($this->barcodes->contains($barcode)) {
$this->barcodes->removeElement($barcode);
// set the owning side to null (unless already changed)
if ($barcode->getProduct() === $this) {
$barcode->setProduct(null);
}
}
return $this;
}
}
and my ProductType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('slug')
->add('picture')
->add('barcodes', CollectionType::class, [
'entry_type' => BarcodeType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false
])
->add('is_activated')
->add('comments')
;
}
In your Product entity, allow the possibility of a null return type by changing Collection to ?Collection:
/**
* #return Collection|Barcode[]|null
*/
public function getBarcodes(): ?Collection
{
return $this->barcodes;
}

Categories