0

我有以下模型关系

Post belongsto PostCategory
PostCategory belongsto Forum
PostSubcat belongsto PostCategory

PostCategory hasmany Post
PostCategory hasmany PostSubcat
Forum hasmany PostCategory.

我正在使用我的 ForumsController add() 方法,但我无法使用标准 find('list') 来显示用户可以添加帖子的所有论坛、类别和子类别。例如下拉应该看起来像......

- Forum #1 Title
    - Category #1.1 Title
        - Subcat #1.1 Title
        - Subcat #1.2 Title
    - Category #1.2 Title
    - Category #1.3 Title
        - Subcat #2.1 Title
        - Subcat #2.2 Title
- Forum #2 Title
    - Category #2.1 Title
    - Category #2.2 Title

所以相反我做了一个 find('all') 像这样......

$forums = $this->Forum->find('all', array(
    'fields' => array('Forum.title'),
    'conditions' => array('Forum.page_id' => $page_id),
    'contain' => array(
        'PostCategory' => array(
            'fields' => array(
                'PostCategory.id', 'PostCategory.title'
            ),
            'PostSubcat' => array(
                'fields' => array(
                    'PostSubcat.id', 'PostSubcat.title'
                ),
            )
        )
    )
));

$this->set('forums', $forums);

我的 add.ctp 论坛有以下代码供选择

<?php if($forums): ?>
    <div class="input select required"><label for="PostCategoryId">Category</label>
    <select name="data[Post][category_id]" id="PostCategoryId">
        <option value="">Select a Category</option>
        <?php foreach($forums as $forum): ?>
            <?php if(!empty($forum['PostCategory'])): ?>
                <option value="" class="SelectSeparator"><?php echo $forum['Forum']['title']; ?></option>
                <?php foreach($forum['PostCategory'] as $category): ?>
                   <?php if($category_id == $category['id']){
                       $selected = "selected";
                   }else{
                       $selected = "not";
                   } ?>
                   <option value="<?php echo $category['id']; ?>" <?php echo $selected;?>><?php echo $category['title']; ?></option>
                   <?php foreach($category['PostSubcat'] as $subcat): ?>
                       <?php if($category_id == $subcat['id']){
                           $selected = "selected";
                       }else{
                           $selected = "not";
                       } ?>
                       <option value="<?php echo $subcat['id']; ?>"<?php echo $selected;?>>-- <?php echo $subcat['title']; ?></option>
                   <?php endforeach; // subcat?>
               <?php endforeach; // category ?>
           <?php endif; // if forum has categories ?>
       <?php endforeach; // forum?>
   </select> 
   </div>
<?php endif; // if there are forums ?>

这将完全按照我想要的方式显示选择选项,并且它可以正确验证 - 如果用户选择论坛标题或选择“选择类别”而不是类别标题,它将不会添加帖子。但是,它不是 Cake 友好的格式,因此不会显示验证错误。

有没有一种方法可以轻松地将其转换为 CakePHP Form->input helper,以便正确显示验证错误消息?

4

0 回答 0