BaseForm.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace ghs\models;
  3. use yii\base\Model;
  4. use common\components\util;
  5. use Yii;
  6. /**
  7. * 管理员表单基类
  8. */
  9. class BaseForm extends Model
  10. {
  11. /**
  12. * 验证表单数据并返回结果
  13. * 如果验证失败,返回错误响应
  14. *
  15. * @return bool 验证是否通过
  16. * @throws \Exception
  17. */
  18. public function validateForm()
  19. {
  20. if (!$this->validate()) {
  21. $errors = $this->getFirstErrors();
  22. $message = reset($errors);
  23. util::fail($message);
  24. }
  25. return true;
  26. }
  27. /**
  28. * 自动加载并验证请求数据
  29. *
  30. * 自动检测请求类型(GET 或 POST),加载对应的数据并进行验证。
  31. * 相比手动指定 $method 参数,使用 $request->isGet 和 $request->isPost
  32. * 是 Yii 框架推荐的做法,更符合框架风格。
  33. *
  34. * 使用示例:
  35. * - POST 请求自动加载:$form->loadAndValidate();
  36. * - GET 请求自动加载:$form->loadAndValidate();
  37. *
  38. * @param string $formName 表单名称,用于嵌套数据
  39. * @return bool 验证成功返回 true,失败自动输出错误响应
  40. * @throws \Exception
  41. */
  42. public function loadAndValidate($formName = '')
  43. {
  44. $request = Yii::$app->request;
  45. // ✨ 优化:使用 Yii 提供的方法检查请求类型
  46. // 相比手动字符串比较 ($method === 'get'),这种方式更符合框架风格
  47. if ($request->isGet) {
  48. $data = $request->get();
  49. } elseif ($request->isPost) {
  50. $data = $request->post();
  51. } else {
  52. util::fail('不支持的请求方法');
  53. }
  54. if (!$this->load($data, '')) {
  55. util::fail('数据加载失败');
  56. }
  57. return $this->validateForm();
  58. }
  59. /**
  60. * 批量设置属性到模型
  61. *
  62. * @param $model 目标模型
  63. * @param array $allowedFields 允许的字段列表
  64. * @return 目标模型
  65. */
  66. public function assignToModel($model, $allowedFields = [])
  67. {
  68. $properties = array_keys($this->attributes);
  69. foreach ($properties as $prop) {
  70. // 如果指定了允许字段列表,检查是否在其中
  71. if (!empty($allowedFields) && !in_array($prop, $allowedFields)) {
  72. continue;
  73. }
  74. if (isset($this->$prop)) {
  75. $model->$prop = $this->$prop;
  76. }
  77. }
  78. return $model;
  79. }
  80. }