<a href="admin.php?op=create&id={$news.id}" class="btn btn-outline-warning">
修改
</a>
admin.php
,先加入 $id
過濾
// 變數過濾
$op = isset($_REQUEST['op']) ? htmlspecialchars($_REQUEST['op']) : 'create';
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
流程 default
加入判斷,是否有 $id
,若有,則呼叫 show()
並將該篇文章內容送到表單供修改,若無則強制 $op
為 create
,以預設載入發布表單。
switch ($op) {
case 'store':
$id = store();
//執行後轉向
header("location: index.php?op=show&id=$id");
exit;
default:
if ($id) {
$smarty->assign('news', show($id));
} else {
$op = 'create';
}
break;
}
show()
在前台的 index.php
中,無法直接這樣呼叫。所以,我們將 show()
搬移至 function.php
檔中,以便 index.php
和 admin.php
都能呼叫templates/admin_create.tpl
,我們要將每個欄位都塞入預設值
<form action="admin.php" method="post" enctype="multipart/form-data">
<div class="mb-3 row">
<label for="title" class="col-sm-3 col-form-label">文章標題</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="title" name="title" placeholder="請輸入文章標題" {if isset($news.title)}value="{$news.title}"{/if}>
</div>
</div>
<div class="mb-3 row">
<label for="content" class="col-sm-3 col-form-label">文章內容</label>
<div class="col-sm-9">
<textarea class="form-control" id="content" name="content" placeholder="請輸入文章內容">{if isset($news.content)}{$news.content}{/if}</textarea>
</div>
</div>
<div class="mb-3 row">
<label for="author" class="col-sm-3 col-form-label">發布者資訊</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="author" name="author" placeholder="請輸入發布者資訊" {if isset($news.author)}value="{$news.author}"{/if}>
</div>
</div>
<div class="mb-3 row">
<label for="date" class="col-sm-3 col-form-label">文章日期</label>
<div class="col-sm-9">
<input type="date" class="form-control" id="date" name="date" placeholder="請選擇文章日期" {if isset($news.date)}value="{$news.date}"{/if}>
</div>
</div>
順便將分類選項的部份也改成活的
<select class="form-select" id="category" name="category">
{foreach $categories as $category_id => $category_title}
<option value="{$category_id}" {if isset($news.category) && $news.category==$category_id}selected{/if}>
{$category_title}
</option>
{/foreach}
</select>
特別注意下方的送出按鈕前須加入隱藏欄位,若是有 $news.id
值的話,表示目前是要修改,所以必須傳送不同的 $op
及 $id
,才知道要改哪篇文章。
<div class="mb-3 row">
<div class="col-sm-9 offset-sm-3">
{if isset($news.id)}
<input type="hidden" name="op" value="update">
<input type="hidden" name="id" value="{$news.id}">
{else}
<input type="hidden" name="op" value="store">
{/if}
<button type="submit" class="btn btn-primary">送出</button>
</div>
</div>
</form>