I have user and phone objects with OneToMany relationships between them.
My custom object:
namespace Project\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
class User
{
private $phone;
public function __construct()
{
$this->phone = new ArrayCollection();
}
public function addPhone(\Project\UserBundle\Entity\Phone $phone)
{
$this->phone[] = $phone;
}
public function getPhone()
{
return $this->phone;
}
}
And my Phone object:
namespace Project\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
class Phone
{
private $user;
private $number;
public function setUser(\Project\UserBundle\Entity\User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
}
I deleted part of the code to make it a little short, I have an Id field and additional fields related to objects.
In my controller, I do this:
public function showFormAction($entity)
{
$user = new User();
$phone = new Phone();
$user->addPhone($phone);
$form = $this->createForm(new UserRegister(), $user);
}
In my form class:
class UserRegister extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('email', 'text')
->add('password', 'repeated', array(
'type' => 'password',
'invalid_message' => 'The password fields must match.',
'options' => array('label' => 'Password'),
'error_bubbling' => false)
)
->add('first_name', 'text')
->add('last_name', 'text')
->add('phone', 'text' );
}
public function getName()
{
return 'register';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Project\UserBundle\Entity\User',
);
}
}
And in my branch template:
<div>
{{ form_errors(form.phone) }}
{{ form_label(form.phone, null, { 'attr': {'class': 'span-3'} } ) }}
{{ form_widget(form.phone, { 'attr': {'class': 'text'} } ) }}
</div>
What I'm trying to do basically is to allow the user to have multiple phone numbers, therefore, to have OneToMany relationship between the user and the phone. In my form, I want to show the "number" field of the "Phone" object in my form, and then add a separate phone record to the appropriate user.
Currently, with the code above, the form is a render, but shows:
"Doctrine\Common\Collections\ArrayCollection @0000000062cf59cf00000000e32fc883" "".
"" "" Twig_Runtime_Error " " 500 ". " form.phone.number", Phone, :
"" " " Symfony\Component\Form\FormView " "
"phone" "entity" , Entity, " ".
, , - , , , , . , , , User, User.