| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace ghs\models;
- use yii\base\Model;
- use common\components\util;
- use Yii;
- /**
- * 管理员表单基类
- */
- class BaseForm extends Model
- {
- /**
- * 验证表单数据并返回结果
- * 如果验证失败,返回错误响应
- *
- * @return bool 验证是否通过
- * @throws \Exception
- */
- public function validateForm()
- {
- if (!$this->validate()) {
- $errors = $this->getFirstErrors();
- $message = reset($errors);
- util::fail($message);
- }
- return true;
- }
- /**
- * 自动加载并验证请求数据
- *
- * 自动检测请求类型(GET 或 POST),加载对应的数据并进行验证。
- * 相比手动指定 $method 参数,使用 $request->isGet 和 $request->isPost
- * 是 Yii 框架推荐的做法,更符合框架风格。
- *
- * 使用示例:
- * - POST 请求自动加载:$form->loadAndValidate();
- * - GET 请求自动加载:$form->loadAndValidate();
- *
- * @param string $formName 表单名称,用于嵌套数据
- * @return bool 验证成功返回 true,失败自动输出错误响应
- * @throws \Exception
- */
- public function loadAndValidate($formName = '')
- {
- $request = Yii::$app->request;
- // ✨ 优化:使用 Yii 提供的方法检查请求类型
- // 相比手动字符串比较 ($method === 'get'),这种方式更符合框架风格
- if ($request->isGet) {
- $data = $request->get();
- } elseif ($request->isPost) {
- $data = $request->post();
- } else {
- util::fail('不支持的请求方法');
- }
- if (!$this->load($data, '')) {
- util::fail('数据加载失败');
- }
- return $this->validateForm();
- }
- /**
- * 批量设置属性到模型
- *
- * @param $model 目标模型
- * @param array $allowedFields 允许的字段列表
- * @return 目标模型
- */
- public function assignToModel($model, $allowedFields = [])
- {
- $properties = array_keys($this->attributes);
- foreach ($properties as $prop) {
- // 如果指定了允许字段列表,检查是否在其中
- if (!empty($allowedFields) && !in_array($prop, $allowedFields)) {
- continue;
- }
- if (isset($this->$prop)) {
- $model->$prop = $this->$prop;
- }
- }
- return $model;
- }
- }
|