簡體   English   中英

Symfony2 - 如何在實體字段或樹枝布局中實現嵌套記錄和遞歸函數?

[英]Symfony2 - How to implement nested records and recursive functions into Entity Field or Twig Layout?

我對使用Symfony2中的實體的嵌套記錄做一個組合框有一個嚴重的疑問。 我已經在http://gediminasm.org/article/tree-nestedset-behavior-extension-for-doctrine-2中閱讀了關於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以及它將被存儲的位置(Controller,Entity等)。 如果有人對使用Twig Extensions處理嵌套記錄有其他想法,那也會很感激。

非常感謝你的幫助。

這就是我們為類別(縮進下拉列表)實現嵌套樹以便在產品編輯表單中使用的方法:

  1. 定義您的Category實體類,如文檔中所示

  2. 向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(); } 
  3. 使用Doctrine2注釋定義與Category實體的產品實體關系(在我們的例子中,我們為一個產品提供多個類別支持)

     class Product { /** * @var ArrayCollection * @ORM\\ManyToMany(targetEntity="Category", cascade={"persist", "remove"}) */ private $categories; ... 
  4. 現在,您只需將以下內容添加到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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM