0

我是 cakephp 新手,在烘焙时无法理解我做错了什么。我使用 cakephp/app 路径来烘焙我的博客,它有两个表:

帖子 Id-integer 设置为自动递增和主键 Title Body Created Modified

评论 id-integer 设置为自动递增和主键 post_id 名称评论创建修改

我打算拥有的关联是帖子有许多评论和评论属于帖子所有模型都通过关联和验证成功烘烤。我的评论 add.ctp 使用下拉列表并要求用户选择他想要评论的帖子。我希望在不询问用户的情况下自动设置帖子。下面是我在 commentscontroller.php 中添加操作的片段

添加操作

public function add() {
    if ($this->request->is('post')) {
        $this->Comment->create();
        if ($this->Comment->save($this->request->data)) {
            $this->Session->setFlash(__('The comment has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The comment could not be saved. Please, try again.'));
        }
    }
    $posts = $this->Comment->Post->find('list');
    $this->set(compact('posts'));
}

add.ctp(评论)

<div class="comments form">
<?php echo $this->Form->create('Comment'); ?>
<fieldset>
    <legend><?php echo __('Add Comment'); ?></legend>
<?php
    echo $this->Form->input('post_id');
    echo $this->Form->input('name');
    echo $this->Form->input('comment');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
    <li><?php echo $this->Html->link(__('List Comments'), array('action' => 'index')); ?></li>
    <li><?php echo $this->Html->link(__('List Posts'), array('controller' => 'posts', 'action' => 'index')); ?> </li>
    <li><?php echo $this->Html->link(__('New Post'), array('controller' => 'posts', 'action' => 'add')); ?> </li>
</ul>

4

1 回答 1

0

我假设您想从您的帖子视图导航以向帖子添加评论。在这种情况下,您的按钮将具有以下形式:

 <?php echo $this->Form->create('comment', array(
        'controller' => 'comment',
        'action' => 'add',
        'type' => 'get'
    ));
    echo $this->Form->input('id', array(
        'type' => 'hidden',
        'id' => 'id',
        'value' => $this->request->data['Post']['id']
    ));
    echo $this->Form->button('New Comment', array(
        'type' => 'submit',
        'class' => 'actionButton'
    ));
    echo $this->Form->end();

    ?>

这将通过 URL 中的 GET 传递帖子 ID,然后您可以在视图中拥有以下内容:

<?php
            if (isset($this->request->query['id'])) {
                echo $this->Form->input('post_id', array(
                    'default' => $this->request->query['id']
                ));
            } else echo $this->Form->input('post_id', array(
                'empty' => '[select]'
            ));?>

然后,这会将帖子的选项默认设置为通过 GET 发送的选项

于 2014-11-12T17:08:49.587 回答