0

コントローラーで

$form = $this->createForm(new ArticleType($this->getUser()), $article);

記事の種類で

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
            ));
        }
    }

    // ...
}

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
                    ));
                }
            });
    }

    // ...
}

回収フォームでのデータ確認処理が動作しません。
この後、ArticleType は別のコレクションである必要があります。
とりあえず、このステージのエラーをクリアしたい。(PHP 5.3)

4

1 に答える 1