azmayogi
(Yogi Azma)
January 6, 2016, 2:22am
1
Hi Guys,
hope you all always in good health.
this is basic knowledge that i don’t know. i have created an upload function but it doesn’t work. i was follow this tutorial http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html .
here are what i did.
Model:
[color="#8B0000 "]public $img_path;[/color]
public function rules()
{
return [
[color="#8B0000"]//[/color][['img_path'], 'required'],
[color="#8B0000"][['img_path'], 'file', 'skipOnEmpty' => false][/color]
];
}
[color="#8B0000 "]public function upload()
{
if ($this->validate()) {
$this->img_path->saveAs('uploads/');
return true;
} else {
return false;
}
}[/color]
Controller:
public function actionCreate()
{
$model = new Img();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
[color="#8B0000"]$model->img_path = UploadedFile::getInstance($model, 'img_path');
if ($model->upload()) {[/color]
return $this->redirect(['view', 'id' => $model->id]);
[color="#8B0000"]}[/color]
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Form:
<?php $form = ActiveForm::begin([color="#8B0000 "][‘options’ => [‘enctype’ => ‘multipart/form-data’]][/color]); ?>
<?= $form->field($model, 'img_path')->[color="#8B0000"]fileInput()[/color] ?>
ok, all saved. i tried to upload, choose the file and click create. after create button clicked, the page wasn’t redirect to any page and error message always same. it seems i don’t choose any files before click the create button but i did.
help me please, which part that i missed or wrong.
thank you.
note:
the brown are done by me.
selvakumar
(Selvakumar Kaliyappan)
January 6, 2016, 3:47am
2
Hi yogaz,
Change your controller action like this, it may solve your problem
public function actionCreate()
{
$model = new Img();
if ($model->load(Yii::$app->request->post())) {
$model->img_path = UploadedFile::getInstance($model, 'img_path');
if($model->img_path){
// $model->upload(); OR
$model->img_path->saveAs('uploads/'.time().'.'.$model->attachment->extension);
$model->img_path = 'uploads/'.time().'.'.$model->attachment->extension;
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', ['model' => $model]);
}
}
azmayogi
(Yogi Azma)
January 6, 2016, 4:14am
3
Hi Selvakumar,
yes, it did it .
thank you so much.
the image successfully uploaded, but the path isn’t save in database yet. im trying to learn the code and try.
i will comeback if i get stuck. haha
once again thanks