在会员中心要更新用户的基本资料记录,但总是失败!
经过分析得知:
1.前端view里渲染的时候,由于数据是从Seller模型里读取的,所以前端生成的元素数据名为Seller(如 Seller[shop_name], Seller['name'],而表单验证的时候使用的是BasicModel,提交后($model->load(...)),需要检查当前类名数组(BasicForm)是否存在,前端数据名与后端数组名不一致,所以导致返回false失败.解决办法想到了有两种:
法一:将前端数组名Seller改为BasicForm,通过ActiveForm实现,向后端看齐,但不知如何实现?
法二:将对数据库的操作放在BasicForm里,这样前端使用的模型也是BasicForm,与后端看齐
不知理解是否有误,或者有更好的解决办法。我这里将表单验证与数据存储分别放在两个不同的Model里了,这样对于表的操作就灵活多了,其它地方肯定也有对这个表进行操作,到时候只需要添加一个表单验证即可。
if ($model->load(Yii::$app->request->post()) && $model->validate()) {...}
这一行总是false,将$model->validate()删除掉也不行。
ShopController.php
<?php
namespace frontend\controllers;
use Yii;
use common\controllers\CommonController;
use frontend\models\BasicForm;
use frontend\models\Seller;
use frontend\models\SellerProduct;
// use yii\base\InvalidParamException;
// use yii\web\BadRequestHttpException;
//
class ShopController extends CommonController {
//基本信息
public function actionBasic() {
$model = new BasicForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//$result = $model->basicSave($this->_userid);
die('保存成功!');
} else {
$errors = $model->getErrors();
var_dump($errors);
echo 'find';
$model = Seller::findOne($this->_userid);
return $this->render('basic', [
'model' => $model,
]);
}
}
//店铺认证
public function actionAuth() {
return $this->render('auth');
}
//水果管理
public function actionProduct() {
$model = SellerProduct::find()
->where(['userid' => $this->_userid])
->orderBy('id')
->all();
return $this->render('product', [
'model' => $model,
]);
}
//修改密码
public function actionCode() {
return $this->render('code');
}
}
BaseForm.php
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use frontend\models\Seller;
/**
* ContactForm is the model behind the contact form.
*/
class BasicForm extends Model
{
public $shop_name;
public $tel;
public $sign;
public $realname;
/**
* @inheritdoc
*/
public function rules()
{
return [
// name, email, subject and body are required
//[['shop_name', 'tel', 'sign', 'realname'], 'required'],
];
}
/**
* @inheritdoc
*/
public function TattributeLabels()
{
/* return [
'verifyCode' => 'Verification Code',
];*/
}
public function basicSave($userid) {
$user = Seller::findOne($userid);
// if ($user === null) {
// throw new NotFoundHttpException;
// }
$user->shop_name = $this->shop_name;
$user->tel = $this->tel;
$user->sign = $this->sign;
$user->realname = $this->realname;
// $user->generateAuthKey();
if ($user->save()) {
return $user;
} else {
var_dump($user->getErrors());
}
return null;
}
}