in Controller
$form = $this->createForm(new ArticleType($this->getUser()), $article);
in ArticleType
class ArticleType extends AbstractType
{
private $appUser;
public function __construct($appUser)
{
$this->appUser = $appUser;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$data = $builder->getData();
$builder->add('name', 'text');
$builder->add('examples', 'collection', array(
'type' => new ExampleType($this->appUser),
'options' => array(
'required' => true,
),
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true,
'prototype' => true
));
if (NULL == $data->getOwner() || $data->getOwner() == $this->appUser) {
$builder->add('status', 'choice', array(
'choices' => array(
'A' => 'A',
'B' => 'B',
'C' => 'C',
),
'required' => true
));
}
}
// ...
}
in ExampleType
// ...
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class ExampleType extends AbstractType
{
private $appUser;
public function __construct($appUser)
{
$this->appUser = $appUser;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) {
$example = $event->getData();
$form = $event->getForm();
// Problem 1 : This $example is null if data already registered example.
// problem 2 : Using $this when not in object context
if (!$example || (null == $example->getOwner() || $example->getOwner() == $this->appUser)) {
$form->add('status', 'choice', array(
'choices' => array(
'A' => 'A',
'B' => 'B',
'C' => 'C',
),
'required' => true
));
}
});
}
// ...
}
Data confirmation process in the collection form does not work.
After this, ArticleType has to be collection from another.
For now, I want to clear the error of this stage.
(in PHP 5.3)