Skip to content

Instantly share code, notes, and snippets.

@defrindr
Last active February 21, 2019 02:47
Show Gist options
  • Save defrindr/25eab6075e76a0205ec4701328540749 to your computer and use it in GitHub Desktop.
Save defrindr/25eab6075e76a0205ec4701328540749 to your computer and use it in GitHub Desktop.
how to uploaded image/photo on yii2
1. goto view , change $form and add field to input file
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
...
<?= $form->field($model,'image)->fileInput() ?> <!-- field to input file -->
...
<?= ActiveForm::end() ?>
2. goto model and add new varible
<?php
namespace \common\models;
use Yii;
use yii\web\Model;
class ModuleProfile extends Model{
public $image; //example, i add this new variable
...
}
```
3. after that, add rule $image
...
public function rules()
{
return [
...
[['image'],'file', 'skipOnEmpty' => true, 'extensions'=>'jpg,jpeg,gif,png', 'maxSize' => 1024*1024*2, 'on'=> ['update','create']],
];
}
...
4. then , goto controller and add "use yii\web\UploadedFile"
<?php
namespace \controllers\ProfileController;
use yii\web\UploadedFile; //add this
...
?>
5. last , change function actionUpdate() and actionCreate() . Example for update
...
public function actionUpdate($id)
{
$model = ModuleProfile::find()->where('id='.$id);
if($model->load(Yii::$app->request->post())){
$model->image = UploadedFile::getIntence($model,'image');
...
} else {
...
}
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment