I have a form where user can load the image. In my controller I have an action called actionUpdate which contains code like this.
Controller
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,
]);
}
}
When I'm submitting the form, I'm being redirected to the same update action url but with blank screen, instead of redirecting to the user's page. Maybe the problem is in my Model's upload function?
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;
}
}
could be, also, that your validation or save don't return 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 ')
}
Please have exception handling (try, catch) in your Model. Never write Model without exception handling.
configure yii_logger db in your machine (you can find it Yii2 docs).
then run
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;
you may see error backtrace if your code is breaking somewhere.
Update code in your actionUpdate
$model->upload($image);
and in your model upload function
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;
}
}
Please update this in your code and check it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.