随時更新予定
アクション名 | 意味 |
---|---|
$this->set(['article' => $article, 'user' => $user])) | Viewに変数を渡すときの書き方 |
$this->set(compact(['article', 'user'])) | キーと変数名が同じ場合の省略記法 |
$this->render('/Posts/show') | レンダリングするビューテンプレートを明示する記法。action名とtemplateのファイル名が異なる時に使う |
Controller
src/Controller/ArticlesController.php
// Controllerに対応したViewファイルを自動で読み込むのをやめたいとき
public $autoRender = false;
public function initialize()
{
parent::initialize();
// Template/Layoutの自動レンダリングをやめたい時
$this->viewBuilder()->disableAutoLayout();
// Template/Layout/default.ctpではなくTemplate/Layout/other.ctpを使ってほしい時(上の記述はコメントアウトする)
$this->viewBuilder()->setLayout('other');
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$articles = $this->paginate($this->Articles);
// アクションごとに個別のレイアウトを使うときはここに書く
$this->viewBuilder()->setLayout('only');
$this->set(compact('articles'));
// ↓$this->autoRenderをfalseにしているときは自分で指定する(ルートパスはsrc/Template)
$this->render('Articles/customindex')
}
Template
Template/Articles/index.ctp
<!-- /articlesにアクセスするとTemplate/Articles/index.ctpがレンダリングされる -->
<h1>Blog articles</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
<th>edit</th>
<th>delete</th>
</tr>
<!-- ここから、$articles のクエリーオブジェクトをループして、投稿記事の情報を表示 -->
<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<!-- 詳細画面に遷移するリンクの書き方 -->
<?= $this->Html->link($article->title, ['action' => 'show', $article->id]) ?>
</td>
<td>
<?= $article->created->format(DATE_RFC850) ?>
</td>
<td>
<!-- 編集画面に遷移するリンクの書き方 -->
<?= $this->Html->link('編集', ['action' => 'edit', $article->id]) ?>
</td>
<td>
<!-- Confirm付き削除フォームの書き方 -->
<?= $this->Form->postLink('削除',
['action' => 'delete', $article->id],
['confirm' => '一度削除するともとに戻せません。削除してよろしいですか?']
)
?>
</td>
</tr>
<?php endforeach; ?>
</table>
Htmlヘルパー
src/Template/Layout/default.ctp
<li><?= $this->Html->link('ログアウト', ['controller' => 'users', 'action' => 'logout']); ?></li>
src/Template/Articles/show.ctp
<div>
<!-- 記事の詳細画面から投稿者の詳細画面(="Template/Users/show.ctp")へ遷移する場合 -->
<?= $this->Html->link($article->author->username, [
'controller' => 'users', 'action' => 'show', $article->author->id
]);
?>
</div>
Formヘルパー
投稿時によく使うパターン
Template/Articles/add.ctp
<!-- /articles/addにアクセスするとTemplate/Articles/add.ctpがレンダリングされる -->
<h1>Add Article</h1>
<?php
<!-- Formヘルパー -->
echo $this->Form->create($article);
echo $this->Form->control('title');
echo $this->Form->control('body', ['rows' => '3']);
echo $this->Form->button(__('Save Article'));
echo $this->Form->end();
?>
サンプル:削除ボタン
Template/Articles/add.ctp
<td>
<!-- Confirm付き削除フォームの書き方 -->
<?= $this->Form->postLink('削除',
['action' => 'delete', $article->id],
['confirm' => '一度削除するともとに戻せません。削除してよろしいですか?']
)
?>
</td>