composer require kartik-v/yii2-widget-fileinput "@dev"
en el modelo:crear un atributo virtual que representará la imagen
var $tmp_image;
en el public function rules() {
...
[['tmp_image'], 'safe'],
[['tmp_image'], 'file', 'extensions'=>'jpg, gif, png'],
...
}
tiene que ser safe para que pueda enviarse junto con el resto de los campos del formulario:
en el form:
importante, cambiar el tipo de dato que maneja el formulario
<?php $form = ActiveForm::begin([
'options'=>['enctype'=>'multipart/form-data']]); ?>
<?php
echo $form->field($model, 'tmp_image')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
'pluginOptions'=>[
'allowedFileExtensions'=>['jpg','gif','png'],
'showUpload' => false,
],
]);
?>
en el controller:
por ejemplo en el action de creacion
$model = new Jugador();
if ($model->load(Yii::$app->request->post())){
$tmp_image = UploadedFile::getInstance ( $model, 'tmp_image' );
if (! is_null ( $tmp_image )) {
$model->picture = $tmp_image->name;
$ext = end ( (explode ( ".", $tmp_image->name )) );
// generate a unique file name to prevent duplicate filenames
$image_name = Yii::$app->security->generateRandomString () . ".{$ext}";
// the path to save file, you can set an uploadPath
$uploadPath = Yii::$app->basePath . DIRECTORY_SEPARATOR . Yii::$app->params ['dir_images_uploads'];
$path = $uploadPath . $image_name;
$tmp_image->saveAs ( $path );
$model->picture = Url::home ( true ) . DIRECTORY_SEPARATOR . Yii::$app->params ['dir_images_uploads'] . $image_name;
}
if($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
}
No hay comentarios:
Publicar un comentario