编辑帖子
app/controllers/posts_controller.php
<?php
class PostsController extends PostsHelper
{
function index()
{
}
function view($id)
{
$this->models['post']->setId($id);
$this->set('data', $this->models['post']->read());
}
function add()
{
if (empty($this->params['data']))
{
$this->render();
}
else
{
if ($this->models['post']->save($this->params['data']))
{
$this->flash('Your post has been saved.','/posts');
}
else
{
$this->set('data', $this->params['data']);
$this->validateErrors($this->models['post']);
$this->render();
}
}
}
function delete($id)
{
if ($this->models['post']->del($id))
{
$this->flash('The post with id: '.$id.' has been deleted.', '/posts');
}
}
function edit($id=null)
{
if (empty($this->params['data']))
{
$this->models['post']->setId($id);
$this->params['data']= $this->models['post']->read();
$this->render();
}
else
{
$this->models['post']->set($this->params['data']);
if ( $this->models['post']->save())
{
$this->flash('Your post has been updated.','/posts');
}
else
{
$this->set('data', $this->params['data']);
$this->validateErrors($this->models['post']);
$this->render();
}
}
}
}
?>
app/views/posts/edit.thtml
<h1>Edit post to blog</h1>
<?php echo $html->formTag('/posts/edit')?>
<input type="hidden" name="data[id]" value="<?php echo $html->tagValue('id')?>"/>
<p>Title: <?php echo $html->inputTag('post/title', 40)?>
<?php echo $html->tagErrorMsg('post/title', 'Title is required.') ?></p>
<p><?php echo $html->areaTag('body') ?>
<?php echo $html->tagErrorMsg('post/body', 'Body is required.') ?></p>
<p><?php echo $html->submitTag('Save') ?></p>
</form>
你也可以在表单标签中用
<?php echo $html->hiddenTag('id')?>
来代替直接使用html的<input>标签。
同时, 在 index.thtml 中, 我们添加一个编辑连接:
<h1>Blog posts</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<?php foreach ($this->post->findAll() as $post): ?>
<tr>
<td><?php echo $post['id']?></td>
<td>
<?php echo $html->linkTo($post['title'], "/posts/view/{$post['id']}")?>
<?php echo $html->linkTo('Delete',"/posts/delete/{$post['id']}", null, "Are you sure you want to delete post entitled \'{$post['title']}\'?")?>
<?php echo $html->linkTo('Edit',"/posts/edit/{$post['id']}")?>
</td>
<td><?php echo $post['created']?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $html->linkTo('Add new post', '/posts/add') ?>