Reputation: 793
I'm trying to embed forms in symfony but I'm not sure what I'm doing wrong. I have two entities. User and Color
User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* @ORM\Table()
* @ORM\Entity
*/
class User
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="Color", cascade={"persist"})
*/
protected $color;
public function getId()
{
return $this->id;
}
public function getColor()
{
return $this->color;
}
public function setColor($color)
{
$this->color = $color;
}
}
Color.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Color
*
* @ORM\Table()
* @ORM\Entity
*/
class Color
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
}
The form is rendered fine but when I try to save the entity I get an error saying Catchable Fatal Error: Object of class AppBundle\Entity\Color could not be converted to string
Here's my controller
.......
$user = new User();
$form = $this->createForm(new SelectionType(), $user);
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new Response(sprintf('ID %s', $user->getId()));
}
SelectionType.php
........
->add('color', new ColorType())
....
So what I'm doing wrong?
Upvotes: 1
Views: 840
Reputation: 29932
Add a __toString()
method to your Color
class
// all declaration here
class Color
{
// all properties here
public function __toString()
{
return $this->name();
}
// all getters and setters here
}
This error is caused because Symfony's Form try to give a "representation for GUI" of your object and, if you don't specify anything else into FormBuilder (or if you don't use any DataTransformer), it will search for a string representation of object (that you can obtain with __toString()
method)
Upvotes: 1