遵循以下http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html中记录的示例
我需要根据类别选择填充子类别字段。我不明白为什么 /article/create 会出现此错误:
FatalErrorException: Error: Call to a member function getSubCategories() on a non-object
表格 :
namespace Cc\HitoBundle\Form\Type;
…
class ArticleType extends AbstractType
{
private $registrationArticleListener;
public function __construct(RegistrationArticleListener $registrationArticleListener)
{
$this->registrationArticleListener = $registrationArticleListener;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
…
->add('category', 'document', array(
'label' => 'Category',
'class' => 'Cc\HitoBundle\Document\Category',
'property' => 'name',
));
$builder->addEventSubscriber($this->registrationArticleListener);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Cc\HitoBundle\Document\Article'
));
}
public function getName()
{
return 'article';
}
}
我不明白说明书中的AddNameFieldSubscriber()函数是什么
聆听者:
namespace Cc\HitoBundle\Form\EventListener;
…
class RegistrationArticleListener implements EventSubscriberInterface
{
/**
* @var FormFactoryInterface
*/
private $factory;
/**
* @var DocumentManager
*/
private $dm;
/**
* @param factory FormFactoryInterface
*/
public function __construct(FormFactoryInterface $factory, $mongo)
{
$this->factory = $factory;
$this->dm = $mongo->getManager();
}
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'preBind',
FormEvents::PRE_SET_DATA => 'preSetData',
);
}
/**
* @param event FormEvent
*/
public function preSetData(FormEvent $event)
{
$agent = $event->getData();
if (null === $article) {
return;
}
$form = $event->getForm();
$subCategories = $article->getCategory()->getSubCategories();
$this->customizeForm($form, $subCategories);
}
public function preBind(FormEvent $event)
{
$data = $event->getData();
$id = $data['event'];
$agent = $this->dm
->getRepository('CcHitoBundle:Article')
->find($id);
if ($article === null) {
$msg = 'The event %s could not be found for you registration';
throw new \Exception(sprintf($msg, $id));
}
$form = $event->getForm();
$subCategories = $article->getCategory()->getSubCategories();
$this->customizeForm($form, $subCategories);
}
protected function customizeForm($form, $subCategories)
{
}
}
而且我不明白我必须在 customizeForm 函数中添加什么。请帮我 !!=)