dongqufi82315 2014-11-29 08:57
浏览 18
已采纳

如何在下拉列表中加载类别名称

I want to load only main categories(not sub-categories) name in drop down list. i have tried enough but could not succeed. There are numbers of answer on this site and I tried to solve my problem in that way but can't. The category table is given below, it is same as on cakephp docs in Tree.

categories table attribute

id | parent_id | lft| rght |name |

i tried these techniques given on following links How to populate drop-down list with database values in CakePHP

full code of controller to create category is given below.

 if ($this->request->is('post')) {
            $this->Category->create();
            if ($this->Category->save($this->request->data)) {
                $this->Session->setFlash(__('Category has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add Category.'));
        }
        else 
          $categories = $this->Category->find('list');
          $this->set(compact('categories'));
           return $this; 
      }

code of category.ctp is

  <?php echo $this->Form->create('Category'); ?>
        <fieldset>
        <legend><?php echo __('Add Category'); ?>
        </legend>
        <?php
                $form->input('id');
        //      echo $this->Form->input('id');
                echo $this->Form->input('name');

        ?>
        </fieldset>
        <?php echo $this->Form->end(__('Submit')); ?>
        </div>

now please suggest me solution to load data in drop down list.

  • 写回答

2条回答 默认 最新

  • dqc42632 2014-11-29 10:15
    关注

    Stick to the conventions and everything's going to be ok. I assume you need the list in your add form to select the parent category (your intent btw is something that you should clarify in your question).

    With trees you want to order by lft, so if you use find('list') you'll have to pass that in the order option, and in order to retrieve only the top-level categories you'll have to pass in a condition that matches all categories where parent_id is null (or the ID of a parent category whichs sub-categories are your "main" categories).

    Controller

    $parents = $this->Category->find('list', array(
        'conditions' => array(
            'Category.parent_id' => null
        ),
        'order' => array(
            'Category.lft' => 'asc'
        )
    ));
    $this->set('parents', $parents);
    

    View

    echo $this->Form->input('parent_id');
    

    For more information see

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!