增
<h2><strong>form 方法构建新增表单</strong></h2>
<ul>
<li>页面模式下
<ul>
<li>通过访问 <code>create</code> 路由, 进入到 <code>AdminController</code> 方法中的 <code>create</code> 方法</li>
<li>在 <code>create</code> 方法中, 调用 <code>form</code> 方法, 并返回新增页面的结构</li>
</ul></li>
<li>弹窗模式下
<ul>
<li>在访问 <code>createButton</code> 方法时, 会调用 <code>form</code> 方法, 并返回新增表单的结构</li>
</ul></li>
</ul>
<pre><code class="language-php">/**
* 前端 amis 通过识别 form 方法返回的结构来构建表单
*
* @param bool $isEdit 用于判断是否为编辑
*
* @return Form
*/
public function form($isEdit)
{
// baseForm 方法中, 处理了表单的一些基础内容
// 可以传入一个 bool 参数, 控制在表单提交成功后是否返回上一页
return $this-&gt;baseForm()-&gt;body([
TextControl::make()-&gt;name('name')-&gt;label('Name'),
TextControl::make()-&gt;name('email')-&gt;label('Email'),
]);
}</code></pre>
<p><br></p>
<h2><strong>store 方法处理新增表单提交</strong></h2>
<ul>
<li>提交的流程
<ul>
<li>前端渲染新增表单 (里面包含了提交的路径)
<ul>
<li>页面模式下, 提交 <code>api</code> 在 <code>AdminController</code> 下的 <code>create</code> 方法中进行了设置</li>
<li>弹窗模式下, 提交 <code>api</code> 在 <code>createButton</code> 方法中进行了设置</li>
</ul></li>
<li>提交到后端, 后端会调用 <code>store</code> 方法, 并进行相应的处理</li>
</ul></li>
<li><code>AdminController</code> 中的 <code>store</code> 方法, 可以满足大多数的新增表单提交需求, 但是如果有特殊的需求, 也可以重写该方法</li>
<li>大多数情况下, 重写对应 <code>service</code> 中的 <code>store</code> 方法即可</li>
</ul>
<pre><code class="language-php">/**
* 新增保存
*
* @param Request $request
*
* @return JsonResponse|JsonResource
*/
public function store(Request $request)
{
$response = fn($result) =&gt; $this-&gt;autoResponse($result, __('admin.save'));
// 处理快速编辑
if ($this-&gt;actionOfQuickEdit()) {
return $response($this-&gt;service-&gt;quickEdit($request-&gt;all()));
}
// 处理快速编辑某项
if ($this-&gt;actionOfQuickEditItem()) {
return $response($this-&gt;service-&gt;quickEditItem($request-&gt;all()));
}
// 返回新增结果
return $response($this-&gt;service-&gt;store($request-&gt;all()));
}
/**
* service 中实际处理新增逻辑的方法, 可以在自己的 service 中重写该方法
*
* @param $data
*
* @return bool
*/
public function store($data): bool
{
$columns = $this-&gt;getTableColumns();
$model = $this-&gt;getModel();
foreach ($data as $k =&gt; $v) {
if (!in_array($k, $columns)) {
continue;
}
$model-&gt;setAttribute($k, $v);
}
return $model-&gt;save();
}</code></pre>