模型表单回调

model-form目前提供了下面几个方法来接收回调函数:

  1. // 在表单提交前调用
  2. $form->submitted(function (Form $form) {
  3. //...
  4. });
  5. //保存前回调
  6. $form->saving(function (Form $form) {
  7. //...
  8. });
  9. //保存后回调
  10. $form->saved(function (Form $form) {
  11. //...
  12. });

可以从回调参数$form中获取当前提交的表单数据:

  1. $form->saving(function (Form $form) {
  2. dump($form->username);
  3. });

获取获取模型中的数据

  1. $form->saved(function (Form $form) {
  2. $form->model()->id;
  3. });

可以直接在回调中返回Symfony\Component\HttpFoundation\Response的实例,来跳转或进入页面:

  1. $form->saving(function (Form $form) {
  2. // 返回一个简单response
  3. return response('xxxx');
  4. });
  5. $form->saving(function (Form $form) {
  6. // 跳转页面
  7. return redirect('/admin/users');
  8. });
  9. $form->saving(function (Form $form) {
  10. // 抛出异常
  11. throw new \Exception('出错啦。。。');
  12. });

返回错误或者成功信息在页面上:

  1. use Illuminate\Support\MessageBag;
  2. // 抛出错误信息
  3. $form->saving(function ($form) {
  4. $error = new MessageBag([
  5. 'title' => 'title...',
  6. 'message' => 'message....',
  7. ]);
  8. return back()->with(compact('error'));
  9. });
  10. // 抛出成功信息
  11. $form->saving(function ($form) {
  12. $success = new MessageBag([
  13. 'title' => 'title...',
  14. 'message' => 'message....',
  15. ]);
  16. return back()->with(compact('success'));
  17. });

删除前后

since v1.6.13

在删除的前后增加了两个回调deletingdeleted

可以直接抛出异常

  1. $form->deleting(function () {
  2. ...
  3. throw new \Exception('产生错误!!');
  4. });
  5. $form->deleted(function () {
  6. ...
  7. throw new \Exception('hahaa');
  8. });

直接返回一个json response,可以用来修改文案提示:

  1. $form->deleting(function () {
  2. ...
  3. return response()->json([
  4. 'status' => false,
  5. 'message' => '删除失败,请。。',
  6. ]);
  7. });
  8. $form->deleted(function () {
  9. ...
  10. return response()->json([
  11. 'status' => false,
  12. 'message' => '删除失败,请。。',
  13. ]);
  14. });