第一步 模仿商品列表的添加页的写法
public function add()
{
$model = D('category');//只需改到此处即可
if(IS_POST)
{
if($model->create(I('post.'), 1))
{
if($id = $model->add())
{
$this->success('添加成功!', U('lst?p='.I('get.p')));
exit;
}
}
$this->error($model->getError());
}
//取出所有的分类
$catData=$model->getTree();
// 设置页面中的信息
$this->assign(array(
'catData'=>$catData,
'_page_title' => '添加分类',
'_page_btn_name' => '分类列表',
'_page_btn_link' => U('lst'),
));
$this->display();
}
完整代码如下:
<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends Controller {
public function add()
{
$model = D('category');
if(IS_POST)
{
if($model->create(I('post.'), 1))
{
if($id = $model->add())
{
$this->success('添加成功!', U('lst?p='.I('get.p')));
exit;
}
}
$this->error($model->getError());
}
//取出所有的分类
$catData=$model->getTree();
// 设置页面中的信息
$this->assign(array(
'catData'=>$catData,
'_page_title' => '添加分类',
'_page_btn_name' => '分类列表',
'_page_btn_link' => U('lst'),
));
$this->display();
}
public function lst(){
//商品列表页
$model=D('category');
$data=$model->getTree();
$this->assign(array(
'data'=>$data,
'_page_title'=>'分类列表',
'_page_btn_name'=>'添加新分类',
'_page_btn_link'=>U('add'),
));
$this->display();
}
public function delete(){
$model=D('category');
if(FALSE!==$model->delete(I('get.id'))){
$this->success('删除成功',U('lst'));
}else{
$this->error("删除失败".$model->getError());
}
}
}
?>
第二步 拿数据在视图层做循环
<layout name="layout" />
<div class="main-div">
<form name="main_form" method="POST" action="__SELF__">
<table cellspacing="1" cellpadding="3" width="100%">
<tr>
<td class="label">上级分类:</td>
<td>
<select name="parent_id">
<option value="0">顶级分类</option>
<?php foreach ($catData as $k => $v): ?>
<option value="<?php echo $v['id']; ?>"><?php echo str_repeat('-', 8*$v['level']) . $v['cat_name']; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<td class="label">分类名称:</td>
<td>
<input size="60" type="text" name="cat_name" />
</td>
</tr>
<tr>
<td colspan="99" align="center">
<input type="submit" class="button" value=" 确定 " />
<input type="reset" class="button" value=" 重置 " />
</td>
</tr>
</table>
</form>
</div>
结果如图所示