tigrov/yii2-photo-widget

Upload photo widget for Yii2

Installs: 14

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 3

Forks: 0

Open Issues: 0

Type:yii2-extension

1.1.0 2019-08-01 07:04 UTC

This package is auto-updated.

Last update: 2024-11-29 06:28:28 UTC


README

Upload photo widget for Yii2.

drawing

Latest Stable Version

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist tigrov/yii2-photo-widget

or add

"tigrov/yii2-photo-widget": "~1.0"

to the require section of your composer.json file.

Usage

It is better to use the extension with yii2-upload-behavior

Once the extension is installed, you can use it as follow:

Create a model with a photo attribute

class Model extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'upload' => [
                 'class' => '\tigrov\uploadBehavior\UploadBehavior',
                 'path' => '@runtime/upload',
                 'attributes' => ['photo'],
                 // 'saveCallback' => ['\tigrov\photoWidget\PhotoWidgetHelper', 'crop'],
                 // or if you need to crop and resize
                 'saveCallback' => function ($model, $attribute, $file, $filename) {
                     $width = 200;
                     $height = 200;
                     \tigrov\photoWidget\PhotoWidgetHelper::crop($model, $attribute, $file, $filename, $width, $height);
                 }
            ],
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['photo'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg,jpeg'],
        ];
    }
}

Create an action in a controller

class FormController extends \yii\web\Controller
{
    public function actionUpload()
    {
        $model = new Model();
        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            \Yii::$app->session->setFlash('success', 'Model is saved.');
            return $this->refresh();
        }

        return $this->render('form', [
            'model' => $model,
        ]);
    }
}

Create a form with the file attribute

<?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'photo')->widget('\tigrov\photoWidget\PhotoWidget') ?>
    <?= Html::submitButton('Submit') ?>
<?php $form::end(); ?>

After submitting the photo it will be saved to specified path.

License

MIT