### dcat-admin Environment Configuration Example Source: https://github.com/zavierd/dcat-admin-doc/blob/main/02-安装.md Example of database connection settings in the Laravel `.env` file required for dcat-admin. Ensure these credentials match your database setup. ```dotenv DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dcat-admin DB_USERNAME=root DB_PASSWORD= ``` -------------------------------- ### Create Laravel Project with Composer Source: https://github.com/zavierd/dcat-admin-doc/blob/main/02-安装.md Installs a new Laravel project using Composer. Specify a version or use the default latest. Ensure PHP and Composer are set up correctly. ```bash composer create-project --prefer-dist laravel/laravel 项目名称 9.* # 或 composer create-project --prefer-dist laravel/laravel 项目名称 ``` -------------------------------- ### Complete dcat-admin Installation Source: https://github.com/zavierd/dcat-admin-doc/blob/main/02-安装.md Runs the final installation command for dcat-admin, setting up necessary database tables and configurations. If a 'Specified key was too long' error occurs, add '\Schema::defaultStringLength(191);' to 'app/Providers/AppServiceProvider.php' boot method, clear tables, and re-run. ```shell php artisan admin:install ``` -------------------------------- ### Basic Quick Create Setup in dcat-admin Source: https://github.com/zavierd/dcat-admin-doc/blob/main/28-快捷创建.md This snippet demonstrates the basic setup for the Quick Create feature in dcat-admin. It initializes the quick create functionality and adds 'name' and 'email' form fields. Ensure that the form field types used here match those defined in the 'form' page for consistency. ```php $grid->quickCreate(function (Grid\Tools\QuickCreate $create) { $create->text('name', '名称'); $create->email('email', '邮箱'); }); ``` -------------------------------- ### Bash: dcat-admin Installation/Upgrade Commands Source: https://github.com/zavierd/dcat-admin-doc/blob/main/87-BETA版本更新日志.md This bash script outlines the commands required to remove an existing dcat-admin installation and then install a specific beta version (v2.0.19-beta or v2.0.18-beta). It includes commands to publish assets, migrations, and run migrations. ```bash composer remove dcat/laravel-admin composer require dcat/laravel-admin:"2.0.19-beta" php artisan admin:publish --assets --migrations --force php artisan migrate ``` -------------------------------- ### 列中添加行 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 演示如何在 dcat-admin 的一个列内部再嵌套添加行。这允许创建更复杂的垂直内容堆叠。 ```php $content->row(function (Row $row) { $row->column(4, 'xxx'); $row->column(8, function (Column $column) { $column->row('111'); $column->row('222'); $column->row('333'); }); }); ``` -------------------------------- ### Implement get Method for Repository (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/58-基本使用.md 展示了`Repository`接口中`get`方法的实现,该方法用于为`Grid`组件提供数据。它接收一个`GridModel`实例,并应返回`array`、`Collection`或`LengthAwarePaginator`类型的数据。 ```php /** * 获取Grid表格数据. * * @param Grid\Model $model * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Collection|array */ public function get(Grid\Model $model) { // Implementation to fetch data for Grid } ``` -------------------------------- ### 添加单行内容到布局 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 演示如何向 dcat-admin 布局中添加一个包含简单文本的单行内容。此方法直接在内容区域添加指定文本。 ```php $content->row('hello') ``` -------------------------------- ### Install Laravel-Excel Package Source: https://github.com/zavierd/dcat-admin-doc/blob/main/27-数据导出.md Installs the Maatwebsite Laravel-Excel package and publishes its service provider. This is required for creating custom export functionalities. ```shell composer require maatwebsite/excel:~2.1.0 php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" ``` -------------------------------- ### 列中添加行并嵌套列 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 展示如何在 dcat-admin 的列内添加的行中,再进一步添加子列。这实现了多层级的复杂布局结构。 ```php $content->row(function (Row $row) { $row->column(4, 'xxx'); $row->column(8, function (Column $column) { $column->row('111'); $column->row('222'); $column->row(function(Row $row) { $row->column(6, '444'); $row->column(6, '555'); }); }); }); ``` -------------------------------- ### Install dcat-admin Package Source: https://github.com/zavierd/dcat-admin-doc/blob/main/02-安装.md Installs the dcat-admin package into an existing Laravel project using Composer. If installation fails, setting 'minimum-stability' to 'dev' in composer.json might resolve the issue. ```shell cd {项目名称} composer require dcat/laravel-admin:"2.*" -vvv ``` -------------------------------- ### PHP: Content::composed 事件回调 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 通过 `Content::composed` 方法可以定义一个回调函数,该函数在所有通过 `Content::row` 或 `Content::body` 方法添加的内容都构建完毕后触发。这对于需要在页面内容完全生成后执行的操作非常有用,例如在 Grid 已渲染后进行数据处理。 ```php use Dcat\Admin\Layout\Content; class IndexController { public function index(Content $content) { Content::composed(function (Content $content) { // Grid已执行render方法 }); return $content->body(function ($row) { $grid = new Grid(...); ... $row->column(12, $grid); }); } } ``` -------------------------------- ### PHP: Content::composing 事件回调 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 使用 `Content::composing` 方法注册的回调函数会在 `DcatAdminLayoutContent::render` 方法被调用时执行。这提供了一个在页面内容正式渲染之前修改或添加内容的钩子,例如动态设置页面视图。 ```php use Dcat\Admin\Layout\Content; Content::composing(function (Content $content) { $content->view('app.admin.content'); }); ``` -------------------------------- ### PHP: 使用 Content::full 构建无导航栏页面 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 通过调用 `Content::full()` 方法,可以渲染出不带菜单栏和顶部导航栏的完整页面。此方法允许使用 Dcat Admin 中的所有功能和组件,适用于登录页面或 IFRAME 加载场景。控制器接收 `Content` 实例,并通过 `full()` 方法和 `body()` 方法渲染视图。 ```php use Dcat\Admin\Layout\Content; class AuthController extends Controller { public function getLogin(Content $content) { if ($this->guard()->check()) { return redirect($this->redirectPath()); } // 使用full方法构建登陆页面 return $content->full()->body(view($this->view)); } ... } ``` -------------------------------- ### 等宽布局设置 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 演示 dcat-admin 的等宽布局功能,通过将列宽度设置为 `0` 来实现。所有列将自动分配等分的宽度。 ```php use DcatAdminLayout\Row; use DcatAdmin\Layout\Content; return Content::make() ->body(function (Row $row) { $row->column(0, 'foo'); $row->column(0, 'bar'); $row->column(0, 'baz'); }); ``` -------------------------------- ### PHP: 实现外部API数据源 Repository Source: https://github.com/zavierd/dcat-admin-doc/blob/main/21-数据来源以及查询条件.md 当数据源来自外部API时,需要覆写 `Repository` 中的 `get` 方法。此方法负责通过HTTP客户端(如 GuzzleHttp)请求API,解析返回数据,并使用 `makePaginator` 方法格式化为表格可识别的分页数据。 ```php getCurrentPage(); // 每页显示行数 $perPage = $model->getPerPage(); // 获取排序字段 [$orderColumn, $orderType] = $model->getSort(); // 获取"scope"筛选值 $city = $model->filter()->input($model->filter()->getScopeQueryName(), '广州'); // 如果设置了其他过滤器字段,也可以通过“input”方法获取值,如: $title = $model->filter()->input('title'); if ($title !== null) { // 执行你的筛选逻辑 } $start = ($currentPage - 1) * $perPage; $client = new \GuzzleHttp\Client(); $response = $client->get("{$this->api}?{$this->apiKey}&city=$city&start=$start&count=$perPage"); $data = json_decode((string)$response->getBody(), true); return $model->makePaginator( $data['total'] ?? 0, // 传入总记录数 $data['subjects'] ?? [] // 传入数据二维数组 ); } } ``` -------------------------------- ### 行内添加多列布局 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 展示如何在 dcat-admin 的同一行内添加多个列。可以通过 `row->column()` 方法指定每列的宽度(总和为12),实现响应式布局。 ```php $content->row(function(Row $row) { $row->column(4, 'foo'); $row->column(4, 'bar'); $row->column(4, 'baz'); }); ``` ```php $content->row(function(Row $row) { $row->column(4, 'foo'); $row->column(8, 'bar'); }); ``` -------------------------------- ### PHP: Content::resolving 事件回调 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 通过 `Content::resolving` 方法可以设置一个回调函数,该函数在 `DcatAdminLayoutContent` 类被实例化时触发。这允许在 Content 对象被创建时进行初始化配置或修改其默认行为,例如设置默认视图。 ```php use Dcat\Admin\Layout\Content; Content::resolving(function (Content $content) { $content->view('app.admin.content'); }); ``` -------------------------------- ### Initializing Git Repository for GitHub Upload Source: https://github.com/zavierd/dcat-admin-doc/blob/main/66-开发扩展.md Provides the command-line steps to initialize a Git repository, add a remote origin, commit initial changes, and push the code to a GitHub repository. ```bash git init git remote add origin https://github.com//.git git add . git commit -am "Initial commit." git push origin master ``` -------------------------------- ### HTML/JavaScript: 登录页面模板与 AJAX 提交 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 在 `Content::full` 构建的页面中,无需在模板中编写 `head` 或引入全局静态资源。只需包含当前页面的 HTML 代码,并可直接使用 Dcat Admin 的组件,如示例中的 AJAX 表单提交功能。页面还可通过 `admin_asset` 引入特定 CSS,并使用 `Dcat.ready` 初始化脚本。 ```html
...
``` -------------------------------- ### PHP Admin Section Injection Source: https://github.com/zavierd/dcat-admin-doc/blob/main/03-1.x升级指南.md Demonstrates how to inject default sections into the admin panel using the Dcat\Admin\Admin::SECTION constant. This replaces the deprecated AdminSection class. It shows an example of injecting content into the HEAD section. ```php use Dcat\Admin\Admin; admin_inject_default_section(Admin::SECTION['HEAD'], function () { return ...; }); ``` -------------------------------- ### Configure Form Block Layout in dcat-admin v2.0 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/03-1.x升级指南.md Illustrates the new way to configure block layouts in dcat-admin forms in v2.0. The `setDefaultBlockWidth` method is deprecated. This example shows how to define blocks with titles, column spans, and nested layouts. ```php $form->block(8, function (Form\BlockForm $form) { $form->title('Basic Settings'); $form->showFooter(); $form->width(9, 2); $form->column(6, function (Form\BlockForm $form) { $form->display('id'); $form->text('name'); $form->email('email'); $form->image('avatar'); $form->password('password'); }); $form->column(6, function (Form\BlockForm $form) { $form->text('username'); $form->email('mobile'); $form->textarea('description'); }); }); $form->block(4, function (Form\BlockForm $form) { $form->title('Block 2'); $form->text('nickname'); $form->number('age'); $form->radio('status')->options(['1' => 'Default', 2 => 'Frozen'])->default(1); $form->next(function (Form\BlockForm $form) { $form->title('Block 3'); $form->date('birthday'); $form->date('created_at'); }); }); ``` -------------------------------- ### Handle Form Responses in dcat-admin v2.0 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/03-1.x升级指南.md Provides examples of handling form responses in dcat-admin v2.0. The `success`, `error`, `redirect`, and `location` methods are removed and replaced by a unified `response()` method chain. This applies to both standard forms and tool forms. ```php $form->saving(function (Form $form) { return $form ->response() ->success('Save successful') ->script('console.log("Executing JS code")') ->redirect('auth/users'); }); // Example for tool forms public function handle(array $input) { ... return $this ->response() ->alert() ->success('Success') ->detail('Detailed content'); } ``` -------------------------------- ### Get Selected Keys Script in BatchAction (JavaScript/PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/60-数据表格.md Provides a PHP example for generating JavaScript code to retrieve the primary keys of selected rows in a batch action. It includes client-side validation to ensure at least one row is selected before proceeding. ```php use Dcat\Admin\Grid\BatchAction; class MyBatchAction extends BatchAction { /** * {@inheritdoc} */ public function actionScript() { $warning = __('No data selected!'); return <<getSelectedKeysScript()} if (key.length === 0) { Dcat.warning('{$warning}'); return ; } Object.assign(data, {_key:key}); JS; } ... } ``` -------------------------------- ### Get Row Index in dcat-admin Grid Source: https://github.com/zavierd/dcat-admin-doc/blob/main/17-行的使用和扩展.md This code demonstrates how to obtain the row index (starting from 0) within a dcat-admin grid. It shows usage within a column's `display` callback and within the `actions` callback for row operations. The index is accessed via `_index` property. ```php // Use in display callback $grid->column('Index')->display(function () { return $this->_index + 1; }); // Use in row action $grid->actions(function ($actions) { $index = $this->_index; ... }); ``` -------------------------------- ### 创建 dcat-admin 分步表单 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/43-分步表单.md 使用 `Form::make` 和 `multipleSteps` 方法创建一个基本的分步表单。支持添加多个步骤,每个步骤可以包含不同的表单字段。表单完成后会跳转到指定的完成页面。 ```php protected function form() { return Form::make(new Model(), function (Form $form) { $form->title('分步表单'); $form->action('step'); $form->disableListButton(); $form->multipleSteps() ->remember() // 记住表单步骤,默认不开启 ->width('950px') ->add('基本信息', function ($step) { $info = ' 表单字段支持前端验证和后端验证混用,前端验证支持H5表单验证以及自定义验证。'; $step->html(Alert::make($info)->info()); $step->text('name', '姓名')->required()->maxLength(20); // h5 表单验证 $step->text('age', '年龄') ->required() ->type('number') ->attribute('max', 150) ->help('前端验证'); $step->radio('sex', '性别')->options(['未知', '男', '女'])->default(0); // 后端验证 $step->text('birthplace', '籍贯') ->rules('required') ->help('演示后端字段验证'); $step->url('homepage', '个人主页'); $step->textarea('description', '简介'); }) ->add('兴趣爱好', function ($step) { $step->tags('hobbies', '爱好') ->options(['唱', '跳', 'RAP', '踢足球']) ->required(); $step->text('books', '书籍'); $step->text('music', '音乐'); // 事件 $step->shown(function () { return <<add('地址', function ($step) { $step->text('address', '街道地址'); $step->text('post_code', '邮政编码'); $step->tel('tel', ' 联系电话'); }) ->done(function () use ($form) { $resource = $form->getResource(0); $data = [ 'title' => '操作成功', 'description' => '恭喜您成为第10086位用户', 'createUrl' => $resource, 'backUrl' => $resource, ]; return view('admin::form.done-step', $data); }); }); } ``` -------------------------------- ### PHP: Grid 支持关联数据 (Repository) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/21-数据来源以及查询条件.md 通过 Repository 实现关联数据支持,可以直接在实例化 Repository 时使用 `with` 方法预加载关联关系。 ```php use App\Admin\Repositories\Movie; // 相当于 MovieModel::with('categories') $grid = new Grid(Movie::with(['categories'])); $grid->categories; ... ``` -------------------------------- ### PHP: 修改文件上传路径 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 使用 `move()` 方法可以指定文件上传的目标目录。该路径相对于 disk 的 root 目录。 ```php $form->file('file')->move('public/upload/image1/'); ``` -------------------------------- ### PHP: 配置 dcat-admin 上传驱动 (config/admin.php) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 在 `config/admin.php` 文件中配置 dcat-admin 的上传设置,指定默认的存储 disk 和各类型文件的上传目录。 ```php 'upload' => [ 'disk' => 'admin', 'directory' => [ 'image' => 'images', 'file' => 'files', ] ], ``` -------------------------------- ### PHP: 配置本地文件存储 (config/filesystems.php) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 配置 `config/filesystems.php` 文件以使用本地存储驱动。这包括定义存储根路径和公共访问 URL。 ```php 'disks' => [ ... , 'admin' => [ 'driver' => 'local', 'root' => public_path('uploads'), 'visibility' => 'public', 'url' => env('APP_URL').'/uploads', ], ], ``` -------------------------------- ### Install Easy Excel Package Source: https://github.com/zavierd/dcat-admin-doc/blob/main/27-数据导出.md Installs the Easy Excel package, which is the default export tool for dcat-admin. This is a prerequisite for using the built-in export features. ```bash composer require dcat/easy-excel ``` -------------------------------- ### PHP: 限制上传文件类型 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 使用 `accept()` 方法限制允许上传的文件类型。可以提供文件扩展名列表或 MIME 类型列表,多个值用逗号分隔。 ```php $form->file('file')->accept('jpg,png,gif,jpeg'); // 可以指定 mimeTypes, 多个用逗号分割 $form->file('file')->accept('jpg,png,gif,jpeg', 'image/*'); ``` -------------------------------- ### Publish dcat-admin Assets and Configuration Source: https://github.com/zavierd/dcat-admin-doc/blob/main/02-安装.md Publishes dcat-admin's assets and configuration files to your Laravel project. This command generates the 'config/admin.php' file, allowing customization of installation paths and database connections. ```shell php artisan admin:publish ``` -------------------------------- ### PHP: 配置七牛云存储 (config/filesystems.php) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 配置 `config/filesystems.php` 文件以使用七牛云存储作为文件存储驱动。需要填写七牛的域名、AccessKey、SecretKey 和 Bucket 等信息。 ```php 'disks' => [ ... , 'qiniu' => [ 'driver' => 'qiniu', 'domains' => [ 'default' => 'xxxxx.com1.z0.glb.clouddn.com', //你的七牛域名 'https' => 'dn-yourdomain.qbox.me', //你的HTTPS域名 'custom' => 'static.abc.com', //你的自定义域名 ], 'access_key'=> '', //AccessKey 'secret_key'=> '', //SecretKey 'bucket' => '', //Bucket名字 'notify_url'=> '', //持久化处理回调地址 'url' => 'http://of8kfibjo.bkt.clouddn.com/', // 填写文件访问根url ], ], ``` -------------------------------- ### 设置 npm 淘宝镜像 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/07-主题与颜色.md 为了加速 npm 包的下载,建议配置 npm 使用淘宝镜像源。执行此命令后,npm 将从淘宝镜像下载包。 ```bash npm config set registry https://registry.npm.taobao.org ``` -------------------------------- ### Example Translation File for Dcat Admin Form Source: https://github.com/zavierd/dcat-admin-doc/blob/main/87-BETA版本更新日志.md Provides an example of a language file structure for translating form fields in Dcat Admin. The 'fields' key maps internal field names to their localized display names. ```php [ 'field1' => '字段1', 'field2' => '字段2', ... ], ]; ``` -------------------------------- ### PHP dcat-admin Grid: 方式二使用 Model::with 关联 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/22-关联关系.md 第二种在dcat-admin Grid中关联`profile`表数据的方法是,在`Grid::make`时直接使用Eloquent模型的`with`方法。这会先加载关联数据,再传递给Grid。 ```php use App\Models\User; use Dcat\Admin\Grid; // 关联 profile 表数据 $grid = Grid::make(User::with(['profile']), function (Grid $grid) { $grid->id('ID')->sortable(); ... }); ``` -------------------------------- ### dcat-admin Form Input Field Example Source: https://github.com/zavierd/dcat-admin-doc/blob/main/23-查询过滤.md An example of an HTML input field within the dcat-admin framework. This input is a text type, uses the 'form-control' class, and dynamically sets its ID, placeholder, name, and initial value based on provided variables. ```html ``` -------------------------------- ### Dcat Admin 扩展版本管理配置文件 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/65-扩展基本使用.md 示例 `version.php` 文件,用于定义扩展的不同版本及其描述和迁移文件。键为版本号,值为包含描述和迁移文件名的数组。 ```php [ '版本描述信息,可以有多条', '描述2...', 'create_operation_log.php', // 版本迁移文件,可以有多条 ], '1.0.1' => [ '版本描述信息,可以有多条', 'update_operation_log.php', // 版本迁移文件 ], ... ]; ``` -------------------------------- ### Integrate with Laravel-S (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/12-常见问题.md Steps to integrate Dcat Admin with Laravel-S. This involves installing the Laravel-S package, publishing its resources, and configuring `config/laravels.php` to include Dcat Admin's service provider and cleaner. Assumes Composer and PHP are installed. ```bash composer require hhxsv5/laravel-s ``` ```bash php artisan laravels publish ``` ```php 'register_providers' => [ Dcat\Admin\AdminServiceProvider::class, ], 'cleaners' => [ ... Hhxsv5\LaravelS\Illuminate\Cleaners\DcatAdminCleaner::class, ] ``` ```bash php bin/laravels start ``` -------------------------------- ### PHP: 图片/文件上传表单字段 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 使用 dcat-admin 的表单构建器创建图片和文件上传字段。这些字段支持本地和云存储,并基于 webuploader 实现。 ```php $form->file('file_column'); $form->image('image_column'); ``` -------------------------------- ### Get Built-in Colors in Dcat Admin (JavaScript) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/07-主题与颜色.md Shows how to access built-in colors using the `Dcat.color` object in JavaScript. It illustrates three methods: direct property access, bracket notation, and the `get` method, all returning the hex color code. ```javascript Admin::script( <<<'JS' // 方式1 var primary = Dcat.color.primary; // 方式2 var primary = Dcat.color['primary']; // 方式3 var primary = Dcat.color.get('primary'); console.log(primary); // 打印 #5c6bc6 JS ); ``` -------------------------------- ### PHP: 文件上传表单可下载 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 调用 `downloadable()` 方法后,文件上传表单会提供一个下载链接,允许用户下载已上传的文件。 ```php $form->file('...')->downloadable(); ``` -------------------------------- ### Dcat Admin 基础卡片初始化 (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/69-数据统计卡片.md 演示如何在 Dcat Admin 的自定义卡片类中重写 `init` 方法来执行初始化操作。这通常用于在卡片构造完成后进行一些默认设置,例如调用 `parent::init()` 并添加其他自定义逻辑。 ```php class MyCard extend Card { protected function init() { parent::init(); // 你的初始化操作 } } ``` -------------------------------- ### Get Built-in Colors in Dcat Admin (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/07-主题与颜色.md Demonstrates how to retrieve built-in color codes using the Dcat Admin's color management service in PHP. It shows how to use the `get` method and magic methods to access color values. If a color is not found, the original value is returned. ```php get('primary'); // 输出 #5c6bc6 // 通过魔术方法获取颜色 echo Admin::color()->primary(); // 输出 #5c6bc6 ``` -------------------------------- ### PHP: 设置上传文件的存储权限 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 通过 `storagePermission()` 方法可以为上传的文件设置文件系统权限。参数通常是一个八进制的权限码,例如 777。 ```php $form->image('picture')->storagePermission(777); ``` -------------------------------- ### Show Tool Action PHP Class (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/62-数据详情.md This PHP code defines a custom 'Copy' action class that extends `AbstractTool`. It includes methods for handling requests, defining button appearance, and optionally setting confirmation dialogs and permissions. The `handle` method demonstrates how to process a request and return a response. ```php getKey(); return $this->response() ->success('Processed successfully.') ->redirect('/'); } /** * 如果只是a标签跳转,则在这里返回跳转链接即可 * * @return string|void */ protected function href() { // 获取主键 $key = $this->getKey(); // 获取当前页其他字段 $username = $this->parent->model()->username; // return admin_url('auth/users'); } // 如果你想自定义动作按钮的HTML,可以重写此方法 public function html() { return parent::html(); } /** * 确认弹窗信息,如不需要可以删除此方法 * * @return string|array|void */ public function confirm() { // return ['Confirm?', 'contents']; } /** * 权限判断,如不需要可以删除此方法 * * @param Model|Authenticatable|HasPermissions|null $user * * @return bool */ protected function authorize($user): bool { return true; } /** * 返回请求接口的参数,如不需要可以删除此方法 * * @return array */ protected function parameters() { return []; } } ``` -------------------------------- ### Dcat Admin 设置卡片标题 (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/69-数据统计卡片.md 演示如何使用 `title` 方法为 Dcat Admin 的卡片设置一个标题。此方法应在 `init` 方法中调用,用于在卡片左上角显示文本标题。 ```php class MyCard extend Card { protected function init() { parent::init(); $this->title('活跃用户'); } } ``` -------------------------------- ### New Users Metric Line Chart Example (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/69-数据统计卡片.md Example of a custom 'New Users' metric using the Line widget. It handles different time ranges (7 days, 30 days, etc.) and dynamically generates chart data and card content. Dependencies include the Dcat Admin framework. ```php title($this->label); $this->dropdown([ '7' => 'Last 7 Days', '28' => 'Last 28 Days', '30' => 'Last Month', '365' => 'Last Year', ]); } /** * 处理请求 * * @param Request $request * * @return mixed|void */ public function handle(Request $request) { $generator = function ($len, $min = 10, $max = 300) { for ($i = 0; $i <= $len; $i++) { yield mt_rand($min, $max); } }; switch ($request->get('option')) { case '365': // 卡片内容 $this->withContent(mt_rand(1000, 5000).'k'); // 图表数据 $this->withChart(collect($generator(30))->toArray()); // 直线 break; case '30': // 卡片内容 $this->withContent(mt_rand(400, 1000).'k'); // 图表数据 $this->withChart(collect($generator(30))->toArray()); // 直线 break; case '28': // 卡片内容 $this->withContent(mt_rand(400, 1000).'k'); // 图表数据 $this->withChart(collect($generator(28))->toArray()); // 直线 break; case '7': default: // 卡片内容 $this->withContent('89.2k'); // 图表数据 $this->withChart([28, 40, 36, 52, 38, 60, 55,]); } } /** * 设置图表数据. * * @param array $data * * @return $this */ public function withChart(array $data) { return $this->chart([ 'series' => [ [ 'name' => $this->label, 'data' => $data, ], ], ]); } /** * 设置卡片内容. * * @param string $content * * @return $this */ public function withContent($content) { return $this->content( <<<'HTML'

{$content}

{$this->label}
HTML ); } } ``` -------------------------------- ### 生成表单动作命令 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/61-数据表单.md 使用 Artisan 命令 `php artisan admin:action` 来生成新的表单动作。命令会引导用户输入动作类型(选择 'form-tool'),动作类名,以及命名空间。 ```bash php artisan admin:action Which type of action would you like to make?: [0] default [1] grid-batch [2] grid-row [3] grid-tool [4] form-tool [5] show-tool [6] tree-tool > 4 Please enter a name of action class: > Copy Please enter the namespace of action class [App\Admin\Actions\Form]: > ``` -------------------------------- ### PHP Bar Chart Card Example Source: https://github.com/zavierd/dcat-admin-doc/blob/main/69-数据统计卡片.md Example of a PHP Bar chart card using Dcat Admin's MetricsBar class. It initializes card content, sets titles, dropdown options, chart colors, handles requests for data, and defines how to display chart and content sections. Dependencies include DcatAdminAdmin, DcatAdminWidgetsMetricsBar, and IlluminateHttpRequest. ```php dark35(); // 卡片内容宽度 $this->contentWidth(5, 7); // 标题 $this->title('Avg Sessions'); // 设置下拉选项 $this->dropdown([ '7' => 'Last 7 Days', '28' => 'Last 28 Days', '30' => 'Last Month', '365' => 'Last Year', ]); // 设置图表颜色 $this->chartColors([ $dark35, $dark35, $color->primary(), $dark35, $dark35, $dark35 ]); } /** * 处理请求 * * @param Request $request * * @return mixed|void */ public function handle(Request $request) { switch ($request->get('option')) { case '7': default: // 卡片内容 $this->withContent('2.7k', '+5.2%'); // 图表数据 $this->withChart([ [ 'name' => 'Sessions', 'data' => [75, 125, 225, 175, 125, 75, 25], ], ]); } } /** * 设置图表数据. * * @param array $data * * @return $this */ public function withChart(array $data) { return $this->chart([ 'series' => $data, ]); } /** * 设置卡片内容. * * @param string $title * @param string $value * @param string $style * * @return $this */ public function withContent($title, $value, $style = 'success') { // 根据选项显示 $label = strtolower( $this->dropdown[request()->option] ?? 'last 7 days' ); $minHeight = '183px'; return $this->content( <<<'HTML'

{$title}

{$value} vs {$label}
View Details
HTML ); } } ``` -------------------------------- ### Creating Action Instances Source: https://github.com/zavierd/dcat-admin-doc/blob/main/59-基本使用.md This static method is used to instantiate an action class. You can pass parameters to the constructor when creating an instance. ```php $action = MyAction::make($param1, $param2...); ``` -------------------------------- ### 应用 no-gutters 移除列间距 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/06-开发前必读.md 展示如何在 dcat-admin 布局的行或列上应用 `noGutters()` 方法,以移除默认的列间距(margin)。这可以使内容填满整个容器宽度。 ```php $content->row(function (Row $row) { // 启用 no-gutters $row->noGutters(); $row->column(9, function (Column $column) { $column->row($this->card(['col-md-12', 20], '#4DB6AC')); $column->row(function (Row $row) { // 启用 no-gutters $row->noGutters(); $row->column(4, $this->card(['col-md-4', 30], '#80CBC4')); $row->column(4, $this->card(['col-md-4', 30], '#4DB6AC')); $row->column(4, function (Column $column) { $column->row(function (Row $row) { // 启用 no-gutters $row->noGutters(); $row->column(6, $this->card(['col-md-6', 30], '#26A69A')); $row->column(6, $this->card(['col-md-6', 30], '#26A69A')); }); }); }); }); }); ``` -------------------------------- ### PHP dcat-admin Grid: 方式三使用 Grid\Model 关联 Source: https://github.com/zavierd/dcat-admin-doc/blob/main/22-关联关系.md 第三种在dcat-admin Grid中关联`profile`表数据的方法是,在`Grid::make`后,通过`$grid->model()->with(['profile'])`来指定加载关联数据。这种方式更加灵活,可以在Grid的配置过程中动态添加关联。 ```php use App\Admin\Repositories\User; use Dcat\Admin\Grid; $grid = Grid::make(new User(), function (Grid $grid) { // 关联 profile 表数据 $grid->model()->with(['profile']); $grid->id('ID')->sortable(); ... }); ``` -------------------------------- ### Dcat Admin Grid Field Translation Example (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/31-字段翻译.md This example illustrates how Dcat Admin automatically reads translations for grid fields from language files. When labels are not explicitly set for grid columns, Dcat Admin attempts to find translations in the specified language pack. It also shows how to manually translate fields using `admin_trans_field` and how the `filter` method utilizes these translations. ```php // Not setting label will automatically read translation from language pack $grid->id(); $grid->name; $grid->age; $grid->class; $grid->filter(function ($filter) { $filter->gt('age'); }); // Above code is equivalent to $grid->name('名称'); $grid->age('年龄'); // Can also be used like this $grid->id(admin_trans_field('id')); $grid->name(admin_trans_field('name')); $grid->age(admin_trans_field('age')); ``` -------------------------------- ### PHP: Configure Data Query with Callbacks using withQuery Source: https://github.com/zavierd/dcat-admin-doc/blob/main/58-基本使用.md The `withQuery` method allows setting up callbacks or parameters for data query operations. It is designed to be used in conjunction with the `toTree` method. It accepts a callable that will be executed during the data fetching process. This is useful for pre-processing or modifying the data client before it's retrieved. ```php queryCallbacks[] = $queryCallback; return $this; } public function toTree() { // 这里演示的代码只是为了说明 withQuery 方法的作用 $client = ...; foreach ($this->queryCallbacks as $callback) { $callback($client); } return Helper::buildNestedArray($client->get()); } } ``` -------------------------------- ### Dcat Admin Global Translation Example (PHP) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/31-字段翻译.md This example shows how to define translations in a `global.php` language file for Dcat Admin. When `admin_trans_field` cannot find a translation for a specific field within the current controller's language file, it falls back to searching in `global.php`. This is useful for fields that appear in multiple data tables across different controllers, allowing for centralized translation management. ```php return [ // Commonly used fields can be placed in global.php for use across all controllers. 'fields' => [ 'id' => 'ID', 'created_at' => 'Creation Time', 'updated_at' => 'Update Time', ], ]; ``` -------------------------------- ### PHP: 配置 dcat-admin 云存储上传 (config/admin.php) Source: https://github.com/zavierd/dcat-admin-doc/blob/main/36-图片-文件上传.md 在 `config/admin.php` 文件中配置 dcat-admin 使用云存储(如七牛云)作为默认上传驱动。这会覆盖之前的本地存储配置。 ```php 'upload' => [ 'disk' => 'qiniu', 'directory' => [ 'image' => 'image', 'file' => 'file', ], ], ```