Yash Sharma Yash Sharma - 1 year ago 143
PHP Question

How to convert an array of objects as string in symfony 3?

I'm getting the following error while implementing the many-to-many relationship in b/w 2 entities(Product & Offer):

Catchable Fatal Error: Object of class FoodBundle\Entity\Product could
not be converted to string

Where Product entity is in relation with the Offer entity.
My aim here was to avail offers to products in many-to-many relationship.

This piece of code is creating it as I guess from the error.

class Offer
public function addProduct(\FoodBundle\Entity\Product $product)
$this->product[] = $product;
return $this;

Please help me out to resolve this issue.

Answer Source

This problem is common when you've created the CRUD automatically.

The problem is that you need to select from a <select> a Product in the Offer form and symfony cannot draw the select because the Product class doesn't specify which field should be rendered.

Go to your Product Entity and add the magic __toString method (provide it if you can) and it should look like :

class Product {

    public function __toString(){
        // Or change the property that you want to show in the select.
        return $this->name;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download