[英]Yii2 request post with name not working due to nested with _csrf array
我想在控制器中使用以下代碼,我認為以下代碼是正確的:
$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();
}
}
在您發布的第一行中,第一個加載調用還包含對UserProfile
的請求。 你錯過了括號。
if ( $user->load(Yii::$app->request->post('User')) && $user->load(Yii::$app->request->post('UserProfile')) )
更新
¿文件實例在表單的哪個字段? 加載的avatar屬性將始終為空,因為文件信息位於$_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.