0

私はcakephpを初めて使用し、ベーキング中に何が間違っているのか理解できません。Cakephp/app パスを使用して、2 つのテーブルを持つブログを作成します。

posts ID-integer が自動インクリメントに設定され、主キーが Title Body Created Modified

コメント id-integer が自動インクリメントに設定され、主キー post_id name コメントが作成され、変更されました

私が意図している関連付けは、投稿 hasMany コメントとコメントの属している投稿です。私のコメント 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 に答える