我想在我的控制器中使用以下代码,我认为下面的代码是正确的:
$user = User::findOne(['username'=>$username]);
$profile = UserProfile::findOne(['user_id' => $user->id]);
if ($user->load(Yii::$app->request->post('User')) && $profile->load(Yii::$app->request->post('UserProfile'))) {
然而,它不起作用并直接进入下面的else语句,但是如果我使用下面的语句,它会在if语句中执行代码:
if ($user->load(Yii::$app->request->post('_csrf')))
当使用var_dump时,我得到以下输出,如下所示,您可以看到用户信息和UserProfile嵌套在这是正确的,如果是这样,我该如何更改第一行才能工作:
array(3) { ["_csrf"]=> string(56) "dsadasdasdasdas==" ["UserProfile"]=> array(3) { ["avatar"]=> string(0) "" ["social"]=> array(3) { ["facebook"]=> string(0) "" ["twitter"]=> string(0) "" ["instagram"]=> string(0) "" } ["bio"]=> string(5) "hello" } ["User"]=> array(3) { ["username"]=> string(22) "fsdfsdfsadminjkhnbnmbb" ["email"]=> string(23) "dasdasdh@yahoo.com" ["password"]=> string(14) "web16prounibar" } }
完整控制器操作
public function actionProfile($username)
{
if (!Yii::$app->user->isGuest && $username == Yii::$app->user->identity->username){
$user = User::findOne(['username'=>$username]);
$profile = UserProfile::findOne(['user_id' => $user->id]);
// load user data with role and validate them
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
// only if user entered new password we want to hash and save it
if ($user->password)
{
$user->setPassword($user->password);
}
$user->save(false);
if ($profile->avatar){
$imageName = Yii::$app->security->generateRandomString() . '-' . $user->username;
$profile->file = UploadedFile::getInstance($profile, 'avatar');
$profile->filename = $imageName.'.'.$profile->file->extension;
$profile->file->saveAs('uploads/avatars/'.$imageName.'.'.$profile->file->extension);
$profile->avatar = '/uploads/avatars/'.$imageName.'.'.$profile->file->extension;
}
$profile->save(false);
return $this->goHome();
}else{
return $this->render('update', [
'user' => $user,
'profile' => $profile,
]);
}
}else{
return $this->goHome();
}
}
答案 0 :(得分:0)
在您发布的第一行中,第一个加载调用还请求UserProfile
。你错过了括号。
if ( $user->load(Yii::$app->request->post('User')) && $user->load(Yii::$app->request->post('UserProfile')) )
<强>更新强>
¿表单的哪个字段有文件实例?加载的头像属性将始终为空,因为文件信息位于$_FILES
,而不是$_POST
。因此,更新的条件是:
$profile->file = UploadedFile::getInstance($profile, 'avatar');
if ($profile->file != null) {
$imageName = Yii::$app->security->generateRandomString() . '-' . $user->username;
$profile->file->saveAs('uploads/avatars/'.$imageName.'.'.$profile->file->extension);
$profile->avatar = $imageName.'.'.$profile->file->extension;
$profile->save(false);
}
您还可以在模型中添加规则验证:
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
信息:https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md