L
L
Luchifer2018-08-16 12:22:02
Yii
Luchifer, 2018-08-16 12:22:02

Yii2 beforesave photo upload how to implement?

hi , how to translate this code to beforesave ?
so everything works, I upload the photo to another time sheet, I need it to work on beforesave

public function actionCreate()
    {
            $model = new Shekil();

        if ($model->load(Yii::$app->request->post())) {
            if(isset($model->photos)){
                $upload = new UploadForm();
                $upload->imageFile= UploadedFile::getInstances($model, 'photos');
                foreach ($upload->imageFile as $photos) {
                    $photos->name = Yii::$app->getSecurity()->generateRandomString(15).'.'.$photos->extension;
                    $array[] = $photos->name;
                }
                if ($upload->uploadMultiplePhoto() && !empty($array)) {
                    $model->save();
                    foreach ($array as $value) {
                        $query = Yii::$app->db->createCommand()->insert('shekiller', [
                            'shekil_id' => $model->id,
                            'image' => $value
                        ]);
                        if(!$query->execute()){
                            break;
                            $model->delete();
                            return $this->redirect(['view', 'id' => $model->id]);
                        }
                    }
                    return $this->redirect(['view', 'id' => $model->id]);
                }else{
                    var_dump($upload->errors);
                }
            }else{
                $model->save();
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

tried to do it myself didn't work

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-08-16
@Luchifer

hi , how to translate this code to beforesave ?

copy and paste, replace $modelwith $this
But only afterSave, because in beforeSave new models do not yet have id

D
Dmitry Bay, 2018-08-16
@kawabanga

1) check at least validate() when loading into the model. Otherwise, it may be that the model does not pass validation, and you redirect and the person loses everything that he entered.
2) You need $model->id to work. You can get it in the afterSave() function;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question