ビューを作成するには、まずコントローラーを以下のようにします。
samples_controller.php
<?php
class SamplesController extends AppController
{
var $scaffold;
//index
function index()
{
$this->set('samples', $this->Sample->findAll());
}
//表示
function view($id = null)
{
$this->Sample->id = $id;
$this->set('sample', $this->Sample->read());
}
//登録
function add()
{
if(!empty($this->data))
{
if($this->Sample->save($this->data))
{
$this->redirect('/samples');
}
}
}
//変更
function edit($id = null)
{
if(empty($this->data))
{
$this->Sample->id = $id;
$this->data = $this->Sample->read();
}
else
{
if($this->Sample->save($this->data['Sample']))
{
$this->redirect('/samples');
}
}
}
}
?>
続いて、ビューの作成です。
ファイルは全て「app/views/samples/」配下に置きます。
indexページのファイル名は「index.thtml」
index.thtml
<h1>一覧</h1>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>番号</th>
<th>タイトル</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach($samples as $sample):
$id = $sample['Sample']['id'];
$title = $sample['Sample']['title'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $title; ?></td>
<td><a href="/cake/samples/view/<?php echo $id;?>/">詳細</a> | <a href="/cake/samples/edit/<?php echo $id?>/">編集</a> | <a href="/cake/samples/delete/<?php echo $id?>/" onclick="return confirm('削除しますか?');">削除</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<a href="/cake/samples/add" >新規追加</a>
表示ページのファイル名は「view.thtml」
view.thtml
<?php
$data=$sample['Sample'];
?>
<table border="1"><tbody>
<tr>
<th>番号</th>
<td><?php echo $data['id'] ?></td>
</tr>
<tr>
<th>タイトル</th>
<td><?php echo $data['title'] ?></td>
</tr>
</tbody></table>
登録ページのファイル名は「add.thtml」
add.thtml
<h1>新規追加</h1>
<form method="post" action="<?php echo $html->url('/samples/add') ?>">
<input type="hidden" name="data[Sample][id]" value="" id="SampleId" />
<label for="SampleTitle">タイトル</label>
<?php echo $html->input('Sample/title', array('size' => '40'))?>
<input type="submit" value="登録" />
</form>
<a href="/cake/samples/" >一覧</a>
変更ページのファイル名は「edit.thtml」
edit.thtml
<h1>変更</h1>
<form method="post" action="<?php echo $html->url('/samples/edit')?>">
<?php echo $html->hidden('Sample/id'); ?>
<label for="SampleTitle">タイトル</label>
<?php echo $html->input('Sample/title', array('size' => '40'))?>
<input type="submit" value="変更" />
</form>
<a href="/cake/samples/" >一覧</a>
コントローラ, ビュー
