L
L
lilwings2020-02-13 01:04:03
Yii
lilwings, 2020-02-13 01:04:03

How to access a variable in a model in yii2?

controller:

public function actionAdd()
{
$model = new Info();

if ( $model->load(Yii::$app->request->post()) ) {
    $model->img_preview = UploadedFile::getInstance($model, 'img_preview');
    $model->img_full = UploadedFile::getInstance($model, 'img_full');

    if ( $model->upload() && $model->save(false) ) {
        Yii::$app->session->setFlash('message', 'Информация добавлена!');

        return $this->refresh();
    }

    Yii::$app->session->setFlash('message', 'Не правильные данные!');
}

return $this->render('add', compact('model'));
}


Model:

class Info extends ActiveRecord
{
    public $img_preview;
    public $img_full;

    public static function tableName()
    {
        return '{{info}}';
    }

    public function rules() {
        return [
            ,
            [['title', 'preview', 'description_seo'], 'filter', 'filter' => 'strip_tags'],
            [['title', 'preview', 'description_seo'], 'trim'],
            [['title', 'preview', 'description_seo'], 'required'],
            [['img_preview', 'img_full'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, jpeg'],
            ['description', 'safe'],
        ];
    }

    public function upload() {
        if ( $this->validate() ) {
            // Создание директории
            $folderName = $this->generateUniqFileName("web/info");
            FileHelper::createDirectory( Yii::getAlias("@frontend/web/img/info/$folderName") );

            // Создание файла
            $imgPreviewName = $folderName . '/' . $this->generateUniqFileName("web/info/$folderName") . '.' . $this->img_preview->extension;
            $this->img_preview->saveAs( Yii::getAlias("@frontend/web/img/info/$imgPreviewName") );

            // Создание Файла
            $imgFullName = $folderName . '/' . $this->generateUniqFileName("web/info/$folderName") . '.' . $this->img_full->extension;
            $this->img_full->saveAs( Yii::getAlias("@frontend/web/img/info/$imgFullName") );

            // Перезаписать файлы их директорией
            $this->img_preview = $imgPreviewName;
            $this->img_full = $imgFullName;

            return true;
        }

        return false;
    }

    public function generateUniqFileName($path) {
        $name = bin2hex(random_bytes(8));

        if ( file_exists( Yii::getAlias("@frontend/$path/$name") ) ) return $this->generateUniqFileName();
        else return $name;
    }
}


How can I store the values ​​of variables in the database?
public $img_preview;
public $img_full;


Everything works except saving the path. Or how can you do it right? Only possible with an example, I read about the second model for saving the file, but did not understand ((

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question