首先我们使用的是交响乐3.4.
我们有一个自引用字段 children
在实体上Category
。因此,一个类别可以有类别子项,而这些类别子项可以有类别子项,依此类推......
class Category
{
/**
* @ORM\Column(type="string")
*/
private $title;
/**
* @ORM\OneToMany(targetEntity="AcmeBundle\Entity\Category", mappedBy="parent")
*/
private $children;
/**
* @ORM\ManyToOne(targetEntity="AcmeBundle\Entity\Category", inversedBy="children")
*/
private $parent;
}
现在我们创建了一个 API 并使用表单功能Symfony 来验证和创建对象和数据。因此,对于类别,我们创建了这个 FormType:
class CategoryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('children', CollectionType::class, [
'entry_type' => CategoryType::class,
'allow_add' => true,
'allow_delete' => true,
'mapped' => false,
'by_reference' => false,
]);
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AcmeBundle\Entity\Category'
));
}
}
这是一个例子API数据数组发送到后端:
array(2) {
[0]=>
array(2) {
["title"]=>
string(9) "Backlight"
["children"]=>
array(3) {
[0]=>
array(2) {
["title"]=>
string(10) "Technology"
["children"]=>
array(0) {
}
}
[1]=>
array(2) {
["title"]=>
string(12) "Panel mount "
["children"]=>
array(0) {
}
}
[2]=>
array(2) {
["title"]=>
string(11) "OEM modules"
["children"]=>
array(0) {
}
}
}
}
[1]=>
array(2) {
["title"]=>
string(13) "Ball diameter"
["children"]=>
array(2) {
[0]=>
array(2) {
["title"]=>
string(18) "No pointing device"
["children"]=>
array(0) {
}
}
[1]=>
array(2) {
["title"]=>
string(9) "Trackball"
["children"]=>
array(0) {
}
}
}
}
}
但是当我们保存并运行这段代码时,我们得到了这个error:
[09-Aug-2018 14:41:13 Europe/Paris] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /Applications/MAMP/htdocs/acme-project/vendor/symfony/symfony/src/Symfony/Component/OptionsResolver/OptionsResolver.php on line 865
[09-Aug-2018 14:41:13 Europe/Paris] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) in /Applications/MAMP/htdocs/acme-project/vendor/symfony/symfony/src/Symfony/Component/Debug/Exception/OutOfMemoryException.php on line 1
呜呜,它seems它陷入 en无限循环创建 FormTypes 的原因是他正在创建和无穷无尽的 Children->children->children->... 集合(OptionsResolver
是参数configureOptions()
FormType 中的函数)
So 我的问题是的,这是否可以通过表单功能实现?或者我应该如何编程?或者我是否必须从 Symfony-Form 功能中删除类别的保存,并且必须编写自己的递归保存函数?
我见过其他人问同样的事情,也没有得到答案:http://forum.symfony-project.org/forum/23/topic/70753.html http://forum.symfony-project.org/forum/23/topic/70753.html