Answer the question
In order to leave comments, you need to log in
How to display an image?
Guys I can not understand anything.
I'm doing tests with loading pictures on Yii2.
Контроллер
<?php
namespace backend\controllers;
use backend\models\UploadedForm;
class CourseController extends SrcController
{
public function actionUpload()
{
$model = new UploadedForm();
if (Yii::$app->request->isPost) {
var_dump ($model); die;
$model->image = UploadedFile::getInstances($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
Модель
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadedForm extends Model
{
/**
* @var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false],
];
}
public function upload()
{
if ($this->validate()) {
var_dump ($this->image); die;
$this->image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
return false;
}
}
}
Форма
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin() ?>
<?= $form->field($model, 'image')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
var_dump ($model); die;
object(backend\models\UploadedForm)#60 (6) { ["image"]=> NULL ["_errors":"yii\base\Model":private]=> NULL ["_validators":"yii\base\Model":private]=> NULL ["_scenario":"yii\base\Model":private]=> string(7) "default" ["_events":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> NULL }
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question