Error on "simple" CollectionType inclusion - php

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;
}

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;
}

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))
;
}

option orphanRemoval is ignored

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')
;
}

Symfony 4 - Object of class could not be converted to String

After looking over the internet and here I didn' find something useful for me.
I'm currently creating a CRUD. Every 'Entreprise' having one or multiple 'Site' and I'm currently doing the CRUD for Site. I've made it by doing the make:form command.
Whhen I'm going to create a site the following error appear :
Catchable Fatal Error: Object of class App\Entity\Entreprise could not
be converted to string
I've tried to add the function __toString() as i saw. But maybe i didn't add it crrectly it changes nothing so I removed it.
My controller to create a site looks like this :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
My SiteType generate by the make:form commande :
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'form' => $form->createView()
]);
}
}
So here are my ENTITY
Entreprise
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_siret;
/**
* #ORM\Column(type="string", length=10)
*/
private $entreprise_telephone;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_salesforce_number;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_compte_client;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $entreprise_APE;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $entreprise_image_link;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Site", mappedBy="entreprise_id")
*/
private $entreprise_id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Catalogue", mappedBy="entreprise_id")
*/
private $entreprise_catalogue_id;
public function __construct()
{
$this->entreprise_id = new ArrayCollection();
$this->entreprise_catalogue_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEntrepriseNom(): ?string
{
return $this->entreprise_nom;
}
public function setEntrepriseNom(string $entreprise_nom): self
{
$this->entreprise_nom = $entreprise_nom;
return $this;
}
public function getEntrepriseSiret(): ?string
{
return $this->entreprise_siret;
}
public function setEntrepriseSiret(string $entreprise_siret): self
{
$this->entreprise_siret = $entreprise_siret;
return $this;
}
public function getEntrepriseTelephone(): ?int
{
return $this->entreprise_telephone;
}
public function setEntrepriseTelephone(int $entreprise_telephone): self
{
$this->entreprise_telephone = $entreprise_telephone;
return $this;
}
public function getEntrepriseSalesforceNumber(): ?string
{
return $this->entreprise_salesforce_number;
}
public function setEntrepriseSalesforceNumber(string $entreprise_salesforce_number): self
{
$this->entreprise_salesforce_number = $entreprise_salesforce_number;
return $this;
}
public function getEntrepriseCompteClient(): ?string
{
return $this->entreprise_compte_client;
}
public function setEntrepriseCompteClient(string $entreprise_compte_client): self
{
$this->entreprise_compte_client = $entreprise_compte_client;
return $this;
}
public function getEntrepriseRaisonSociale(): ?string
{
return $this->entreprise_raison_sociale;
}
public function setEntrepriseRaisonSociale(string $entreprise_raison_sociale): self
{
$this->entreprise_raison_sociale = $entreprise_raison_sociale;
return $this;
}
public function getEntrepriseAPE(): ?string
{
return $this->entreprise_APE;
}
public function setEntrepriseAPE(string $entreprise_APE): self
{
$this->entreprise_APE = $entreprise_APE;
return $this;
}
public function getEntrepriseImageLink(): ?string
{
return $this->entreprise_image_link;
}
public function setEntrepriseImageLink(?string $entreprise_image_link): self
{
$this->entreprise_image_link = $entreprise_image_link;
return $this;
}
/**
* #return Collection|Site[]
*/
public function getEntrepriseId(): Collection
{
return $this->entreprise_id;
}
public function addEntrepriseId(Site $entrepriseId): self
{
if (!$this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id[] = $entrepriseId;
$entrepriseId->setEntrepriseId($this);
}
return $this;
}
public function removeEntrepriseId(Site $entrepriseId): self
{
if ($this->entreprise_id->contains($entrepriseId)) {
$this->entreprise_id->removeElement($entrepriseId);
// set the owning side to null (unless already changed)
if ($entrepriseId->getEntrepriseId() === $this) {
$entrepriseId->setEntrepriseId(null);
}
}
return $this;
}
}
And here is
Site
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\SiteRepository")
*/
class Site
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_nom;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_raison_sociale;
/**
* #ORM\Column(type="string", length=255)
*/
private $site_APE;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Client", mappedBy="site_id")
*/
private $site_id;
/**
* #ORM\OneToOne(targetEntity="App\Entity\Adresse", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $adresse_id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="entreprise_id")
* #ORM\JoinColumn(nullable=false)
*/
private $entreprise_id;
public function __construct()
{
$this->site_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getSiteNom(): ?string
{
return $this->site_nom;
}
public function setSiteNom(string $site_nom): self
{
$this->site_nom = $site_nom;
return $this;
}
public function getSiteRaisonSociale(): ?string
{
return $this->site_raison_sociale;
}
public function setSiteRaisonSociale(string $site_raison_sociale): self
{
$this->site_raison_sociale = $site_raison_sociale;
return $this;
}
public function getSiteAPE(): ?string
{
return $this->site_APE;
}
public function setSiteAPE(string $site_APE): self
{
$this->site_APE = $site_APE;
return $this;
}
/**
* #return Collection|Client[]
*/
public function getSiteId(): Collection
{
return $this->site_id;
}
public function addSiteId(Client $siteId): self
{
if (!$this->site_id->contains($siteId)) {
$this->site_id[] = $siteId;
$siteId->addSiteId($this);
}
return $this;
}
public function removeSiteId(Client $siteId): self
{
if ($this->site_id->contains($siteId)) {
$this->site_id->removeElement($siteId);
$siteId->removeSiteId($this);
}
return $this;
}
public function getAdresseId(): ?Adresse
{
return $this->adresse_id;
}
public function setAdresseId(Adresse $adresse_id): self
{
$this->adresse_id = $adresse_id;
return $this;
}
public function getEntrepriseId(): ?Entreprise
{
return $this->entreprise_id;
}
public function setEntrepriseId(?Entreprise $entreprise_id): self
{
$this->entreprise_id = $entreprise_id;
return $this;
}
public function __toString()
{
return $this->getSiteNom();
}
}
I didn't know what's wrong. Maybe the __toString I didn't write correclty !
I've wrote :
public function __toString()
{
return $this->getSiteNom();
}
}
Catchable Fatal Error: Object of class App\Entity\Entreprise
You need to implement the __toString() method in the Entreprise entity
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\EntrepriseRepository")
*/
class Entreprise
{
//...
public function __toString()
{
return $this->entreprise_nom;
}
// ...
}

Categories