我非常怀疑是否要用Symfony2中实体的嵌套记录创建组合框。我在中阅读了关于条令2的嵌套树扩展http://gediminasm.org/article/tree-nestedset-behavior-extension-for-doctrine-2,看起来很有趣,但它并没有提到如何将这个嵌套树实现为表单中的实体字段
此外,我已经阅读了更多关于PHP中递归函数的内容,并且我发现了一个有趣的博客,在那里对它进行了分析,下面是链接http://www.sitepoint.com/hierarchical-data-database/,它特别解释了这个递归函数:
function display_children($parent, $level) {
// Retrieve all children of $parent
$result = mysql_query('SELECT title FROM tree WHERE parent="'.$parent.'"');
// Display each child
while ($row = mysql_fetch_array($result)) {
// Indent and display the title of this child
echo str_repeat(' ',$level).$row['title']."'n";
// Call this function again to display this child's children
display_children($row['title'], $level+1);
}
}
有人知道如何将此代码转换为Symfony2,以及它将存储在哪里(控制器、实体等)。如果有人对使用Twig Extensions处理嵌套记录有其他想法,也将不胜感激。
非常感谢你的帮助。
这就是我们如何实现用于产品编辑表单的类别嵌套树(缩进下拉列表):
-
如文档中所示,定义您的类别实体类
-
向Category实体类添加一个方法,该方法显示按嵌套级别缩进的名称
/** * @ORM'Table() * @ORM'Entity(repositoryClass="CP'YourBundle'Entity'CategoryRepository") * @Gedmo'Tree(type="nested") */ class Category { public function getOptionLabel() { return str_repeat( html_entity_decode(' ', ENT_QUOTES, 'UTF-8'), ($this->getLevel() + 1) * 3 ) . $this->getName(); }
-
使用Doctrine2注释定义与Category实体的产品实体关系(在我们的案例中,一个产品支持多个类别)
class Product { /** * @var ArrayCollection * @ORM'ManyToMany(targetEntity="Category", cascade={"persist", "remove"}) */ private $categories; ...
-
现在,您所要做的就是将以下内容添加到ProductType表单类中
class ProductType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $builder ->add('categories', null, array('property' => 'optionLabel')); }
现在,表单应该显示具有正确缩进的类别列表
您可以查看这个不是基于嵌套集而是基于实体化路径的树实现:https://github.com/KnpLabs/materialized-path。
您可以想象使用它的API来获得树的平面结果集,就像您的代码片段:
$root = $repo->find($id);
$repo->buildTree($root);
$flatArray = $root->toFlatArray(function(NodeInterface $node) {
$pre = $node->getLevel() > 1 ? implode('', array_fill(0, $node->getLevel(), '--')) : '';
return $pre.(string)$node;
});
return $this->get('templating')->render('::tree.html.twig', $flatArray);