fastadmin在前台会员中心里添加后台CRUD生成的表格

视频教程:https://www.bilibili.com/video/BV1Ee41197RX/

 

如图所示,在前台会员中心增加一个表格,功能和后台的一模一样,具有新增 修改 删除 批量删除 搜索 分页 等完整功能!

image

实现逻辑:

一个字:“复制”!

先在后台一键crud生成表格,然后在前台对应位置复制粘贴对应的功能即可!当然有一些地方是要修改的,否则会报方法错误!

1.新建数据表fa_ceshi,然后一键crud

这个很简单,不做具体演示了。

下面的例子里,我们这里生成的是Ceshi,前台要增加的是Mstable。

2.新建模型 Mstable.php

在index文件夹下,新建文件夹model,然后在model文件夹下新建Mstable.php文件,作为模型,复制上面生成的模型文件,注意修改namespace为 namespace app\index\model ,table表名为 mstable。

代码如下:

namespace app\index\model;

use think\Model;

class Mstable extends Model
{
    // 表名
    protected $name = 'mstable';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];
}

3.新建控制器Mstable.php

在index->controller文件夹下新建Mstable.php文件,作为控制器,然后接下来是复制代码。

首先要复制一个会员中心的user控制器代码;

然后去application/admin/library/traits/Backend.php里面复制index add edit del 方法到当前控制器里,这里需要注意,一定要删除关于管理员验证的一些代码,具体我们在视频里有讲解;

然后我们需要在_initialize里加上model:

$this->model = new \app\index\model\Mstable;
 
最后一定记得引入需要的东西
use Exception;

use think\Db;

use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

最终的控制器代码如下:

namespace app\index\controller;

use app\common\controller\Frontend;

use Exception;

use think\Db;

use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;


class Mstable extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        // $auth = $this->auth;
        $this->model = new \app\index\model\Mstable;
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->view->assign('title', "表格");
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage,则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = "";
     /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (array_key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else if (array_key_exists($this->excludeFields, $params)) {
            unset($params[$this->excludeFields]);
        }
        return $params;
    }

     /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
       
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}

4.新建视图(html代码)

在index的view文件夹下新建文件夹mstable,然后把后台ceshi里的index.html add.html和edit.html文件复制进来,index.html里删除关于auth验证的代码。

image

其他两个文件无需修改,index.html改完的代码如下:

<div id="content-container" class="container">
    <div class="row">
        <div class="col-md-3">
            {include file="common/sidenav" /}
        </div>
        <div class="col-md-9">
            <div class="panel panel-default">
                <div class="panel-body">
                    <h2 class="page-header">测试表格</h2>
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane fade active in" id="one">
                            <div class="widget-body no-padding">
                                <div id="toolbar" class="toolbar">
                                    <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
                                    <a href="javascript:;" class="btn btn-success btn-add" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
                                    <a href="javascript:;" class="btn btn-success btn-edit btn-disabled disabled" title="{:__('Edit')}" ><i class="fa fa-pencil"></i> {:__('Edit')}</a>
                                    <a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a>
                                    
            
                                    
            
                                    
                                </div>
                                <table id="table" class="table table-striped table-bordered table-hover table-nowrap"
                                    data-operate-edit="true"
                                    data-operate-del="true"
                                       width="100%">
                                </table>
                            </div>
                        </div>
            
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

5.新建js文件

© 版权声明
THE END
喜欢就支持一下吧
点赞16 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    请登录后查看评论内容