BaseForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. return false;
  25. }
  26. return true;
  27. }
  28. /**
  29. * 自动加载并验证请求数据
  30. *
  31. * 自动检测请求类型(GET 或 POST),加载对应的数据并进行验证。
  32. * 相比手动指定 $method 参数,使用 $request->isGet 和 $request->isPost
  33. * 是 Yii 框架推荐的做法,更符合框架风格。
  34. *
  35. * 使用示例:
  36. * - POST 请求自动加载:$form->loadAndValidate();
  37. * - GET 请求自动加载:$form->loadAndValidate();
  38. *
  39. * @param string $formName 表单名称,用于嵌套数据
  40. * @return bool 验证成功返回 true,失败自动输出错误响应
  41. * @throws \yii\base\InvalidConfigException
  42. */
  43. public function loadAndValidate($formName = '')
  44. {
  45. $request = Yii::$app->request;
  46. // ✨ 优化:使用 Yii 提供的方法检查请求类型
  47. // 相比手动字符串比较 ($method === 'get'),这种方式更符合框架风格
  48. if ($request->isGet) {
  49. $data = $request->get();
  50. } elseif ($request->isPost) {
  51. $data = $request->post();
  52. } else {
  53. util::fail('不支持的请求方法');
  54. return false;
  55. }
  56. if (!$this->load($data, '')) {
  57. util::fail('数据加载失败');
  58. return false;
  59. }
  60. return $this->validateForm();
  61. }
  62. /**
  63. * 批量设置属性到模型
  64. *
  65. * @param $model 目标模型
  66. * @param array $allowedFields 允许的字段列表
  67. * @return 目标模型
  68. */
  69. public function assignToModel($model, $allowedFields = [])
  70. {
  71. $properties = array_keys($this->attributes);
  72. foreach ($properties as $prop) {
  73. // 如果指定了允许字段列表,检查是否在其中
  74. if (!empty($allowedFields) && !in_array($prop, $allowedFields)) {
  75. continue;
  76. }
  77. if (isset($this->$prop)) {
  78. $model->$prop = $this->$prop;
  79. }
  80. }
  81. return $model;
  82. }
  83. }