改
<h2><strong>form 方法构建编辑表单</strong></h2>
<ul>
<li>页面模式下
<ul>
<li>通过访问 <code>edit</code> 路由, 进入到 <code>AdminController</code> 方法中的 <code>edit</code> 方法</li>
<li>在 <code>edit</code> 方法中, 调用 <code>form</code> 方法, 并返回新增页面的结构</li>
</ul></li>
<li>弹窗模式下
<ul>
<li>在访问 <code>rowEditButton</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>update 方法处理编辑表单提交</strong></h2>
<ul>
<li>提交的流程
<ul>
<li>前端渲染编辑表单 (里面包含了提交的路径)
<ul>
<li>页面模式下, 提交 <code>api</code> 和查询回显数据的 <code>api</code> 在 <code>AdminController</code> 下的 <code>edit</code> 方法中进行了设置</li>
<li>弹窗模式下, 提交 <code>api</code> 和查询回显数据的 <code>api</code> 在 <code>rowEditButton</code> 方法中进行了设置</li>
</ul></li>
<li>提交到后端, 后端会调用 <code>update</code> 方法, 并进行相应的处理</li>
</ul></li>
<li><code>AdminController</code> 中的 <code>update</code> 方法, 可以满足大多数的编辑表单提交需求, 但是如果有特殊的需求, 也可以重写该方法</li>
<li>大多数情况下, 重写对应 <code>service</code> 中的 <code>update</code> 方法即可</li>
</ul>
<pre><code class="language-php">/**
* 编辑保存
*
* @param Request $request
*
* @return JsonResponse|JsonResource
*/
public function update(Request $request)
{
$result = $this-&gt;service-&gt;update($this-&gt;getPrimaryValue($request), $request-&gt;all());
return $this-&gt;autoResponse($result, __('admin.save'));
}
/**
* service 中实际处理修改逻辑的方法, 可以在自己的 service 中重写该方法
*
* @param $primaryKey
* @param $data
*
* @return bool
*/
public function update($primaryKey, $data): bool
{
$columns = $this-&gt;getTableColumns();
$model = $this-&gt;query()-&gt;whereKey($primaryKey)-&gt;first();
foreach ($data as $k =&gt; $v) {
if (!in_array($k, $columns)) {
continue;
}
$model-&gt;setAttribute($k, $v);
}
return $model-&gt;save();
}</code></pre>
<h2><strong>数据回显</strong></h2>
<ul>
<li>请求数据的 <code>api</code> 会携带 <code>_action=getData</code> 的参数, 从而调用 <code>service</code> 中的 <code>getEditData</code> 方法</li>
<li>如果是弹窗模式, 编辑表单可以从列表中获取数据并回显</li>
</ul>
<pre><code class="language-php">/**
* 获取编辑页面
*
* @param $id
*
* @return JsonResponse|JsonResource
*/
public function edit($id)
{
$this-&gt;isEdit = true;
if ($this-&gt;actionOfGetData()) {
return $this-&gt;response()-&gt;success($this-&gt;service-&gt;getEditData($id));
}
// ...
}
/**
* 编辑 获取数据 (Service 中)
*
* @param $id
*
* @return Model|\Illuminate\Database\Eloquent\Collection|Builder|array|null
*/
public function getEditData($id)
{
$model = $this-&gt;getModel();
return $this-&gt;query()-&gt;find($id)-&gt;makeHidden([$model-&gt;getCreatedAtColumn(), $model-&gt;getUpdatedAtColumn()]);
}</code></pre>