I have 3 entities User
class User extends BaseUser
{
/**
* @ORM\OneToMany(targetEntity="UserPathologie", mappedBy="user")
*/
protected $userPathologies;
}
Pathologie
class Pathologie
{
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* @ORM\OneToMany(targetEntity="UserPathologie", mappedBy="pathologie")
*/
protected $userPathologies;
}
UserPathologie
class UserPathologie
{
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="userPathologies")
*/
protected $user;
/**
* @ORM\ManyToOne(targetEntity="Pathologie", inversedBy="userPathologies")
*/
protected $pathologie;
/**
* @var boolean
*
* @ORM\Column(name="atteint", type="boolean")
*/
private $atteint;
/**
* @var string
*
* @ORM\Column(name="cause", type="text")
*/
private $cause;
}
Then, on the User form, I want to have the list of all "Pathologies" with the checkbox "atteint" and textarea "cause".
ex:
--label-- Pathologies --/label--
Pathologie A : Yes/No - Textarea cause
Pathologie B : Yes/No - Textarea cause
Pathologie C : Yes/No - Textarea cause
Pathologie D : Yes/No - Textarea cause
Pathologie E : Yes/No - Textarea cause
I proceed like below but the inconvenient is that each line should be added dynamically with javascript and the "pathologies" are in a select field.
in UserRegiterType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('userPathologies', 'collection', array(
'type' => new UserPathologieType(),
'label' => false,
'allow_add' => true,
));
}
And in UserPathologieType, I have
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pathologie')
->add('atteint', 'checkbox', array(
'label' => false,
'required' => false,
))
->add('cause', 'textarea', array(
'label' => 'Cause',
'required' => false,
));
}
This is how I did to get it work
First add
cascade={"persist"}
to the OneToMany relation in User to persist automatically the user pathologiesThen, add all pathologies to the new entity as @Hpatoio suggested
And in the twig template, I used again a loop to get the expected result
To avoid
patologies
in select field override the widget for the fieldSee http://symfony.com/doc/current/book/forms.html#form-theming for details about for theming
Or depending on how you are rendering your collection you can also take this way: Symfony2 formbuilder - entity readonly field as label
To have all pathologies connected to a new user just add them in the
__construct
ofUser