[英]Yii2: $model->load() returns false
我有一個用戶可以加載圖像的表單。 在我的控制器中,我有一個名為actionUpdate的動作,它包含這樣的代碼。
調節器
public function actionUpdate()
{
$id = Yii::$app->user->id;
$model = Page::find()->where(['user_id'=>$id])->one();
if ($model->load(Yii::$app->request->post()))
{
$image = UploadedFile::getInstance($model, 'thumbnail');
$model->thumbnail = $model->url.".".$image->extension;
if ($model->validate() && $model->save())
{
$model->upload();
//page/url is for the user's page
return $this->redirect('page/'.$model->url);
}
}
else
{
//'update' is a view file with form
return $this->render('update', [
'model' => $model,
]);
}
}
當我提交表單時,我將被重定向到相同的更新操作URL,但屏幕為空白,而不是重定向到用戶頁面。 也許問題出在我的Model的上傳功能中?
模型
public function upload()
{
if ($this->validate()) {
$user = Page::find()->where(["user_id" => Yii::$app->user->id])->one();
$this->thumbnail->saveAs('avatars/'.$user->url.'.'.$this->thumbnail->extension);
return true;
} else {
return false;
}
}
也可能是您的驗證或保存不會返回true
if ($model->validate() && $model->save())
{
$model->upload();
//page/url is for the user's page
return $this->redirect('page/'.$model->url);
} else {
var_dump('not validated or not saved ')
}
請在您的模型中進行異常處理(嘗試,捕獲)。 永遠不要在沒有異常處理的情
在你的機器中配置yii_logger db(你可以找到它Yii2 docs)。
然后運行
SELECT FROM_UNIXTIME(log_time, '%Y-%m-%d') log_date, y.* FROM yii_logger y where level = 1 order by log_time desc limit 20;
如果您的代碼在某個地方破壞,您可能會看到錯誤回溯。
更新actionUpdate中的代碼
$model->upload($image);
並在您的模型上傳功能
public function upload($image)
{
if ($this->validate()) {
$user = Page::find()->where(["user_id" => Yii::$app->user->id])->one();
// updated with parameter here
$image->saveAs('avatars/'.$user->url.'.'.$image->extension);
return true;
} else {
return false;
}
}
請在您的代碼中更新此內容並進行檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.