我有基于Symfony2框架的网站,它有三个级别的系统。现在我想创建用于创建新产品的表单。产品还包含有关其类别,子类别以及子子类别的信息。
因此,目标是创建表单,该表单根据之前的选择自动生成子类别和子子类别的选择(当我选择类别时,生成该类别的子类别选项,当我选择子类别选项时,生成子类别)。子类别选择是正确生成的(我遵循Symfony2文档:我使用了Form Events)。我不知道如何为Subsubcategory实体正确设置事件。
这是我的代码(JavaScript工作正常,所以我跳过它):
ProductType代码段
$categoryFormModifer = function(FormInterface $formInterface, Category $category = null) {
$subcategories = null == $category ? array() : $category->getSubcategories();
$formInterface->add('idSubcategory', 'entity', array(
'label' => "Podkategória",
'class' => 'SalalajDefaultBundle:Subcategory',
'choice_label' => 'subTitle',
'placeholder' => '',
'choices' => $subcategories,
));
};
$builder->get('idCategory')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($categoryFormModifer) {
$categoryFormModifer($event->getForm()->getParent(), $event->getForm()->getData());
}
);
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($categoryFormModifer) {
/**
* @var $data Product
*/
$data = $event->getData();
$form = $event->getForm();
$categoryFormModifer($form, $data->getIdCategory());
$subcategory = $data->getIdSubcategory();
$form->add('idSubsubcategory', 'entity', array(
'label' => "Podpodkategoria",
'class' => 'SalalajDefaultBundle:Subsubcategory',
'choice_label' => 'ssbTitle',
'placeholder' => '',
'choices' => $subcategory ? $subcategory->getIdSubsubcategory() : array()
));
}
);
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
/**
* @var $subcategory Subcategory
*/
if (!in_array('idSubcategory', $data))
return;
$subcategory = $data['idSubcategory'];
$form->add('idSubsubcategory', 'entity', array(
'label' => "Podpodkategoria",
'class' => 'SalalajDefaultBundle:Subsubcategory',
'choice_label' => 'ssbTitle',
'placeholder' => '',
'choices' => $subcategory ? $subcategory->getIdSubsubcategory() : array(),
));
}
);
感谢您的帮助!