模型表单回调

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

  1. //保存前回调
  2. $form->saving(function (Form $form) {
  3. //...
  4. });
  5. //保存后回调
  6. $form->saved(function (Form $form) {
  7. //...
  8. });

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

  1. $form->saving(function (Form $form) {
  2. dump($form->username);
  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. });