此處我以裝置號device_no (硬體唯一識別碼,字串型別)為例:
常規的值唯一驗證寫法:
$table = $form->repository()->model()->getTable();
$connection = config('admin.database.connection');
$id = $form->getKey();
$form->text('device_no')->required()
->creationRules(['required', "unique:{$connection}.{$table}"])
->updateRules(['required', "unique:{$connection}.{$table},device_no,$id"])->width(6)->required();
帶自定義查詢條件的寫法:
在提交前檢查回撥裡定義,(注意where方法引數),搭配 responseValidationMessages 方法在表單對應input裡提示驗證錯誤。
$form->submitted(function (Form $form) {
if ($form->isCreating()) {
if (DeviceInfo::where('device_no', $form->device_no)->where('yard_id', '>', '0')->exists()) {
$form->responseValidationMessages('device_no', '此裝置已經被繫結了');
}
} elseif ($form->isEditing()) {
if (DeviceInfo::where('device_no', $form->device_no)->where('yard_id', '>', '0')->where('id', '!=', $form->model()->id)->exists()) {
$form->responseValidationMessages('device_no', '此裝置已經被繫結了');
}
}
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結