PHP code example of shurik2k5 / yii2-upload-behavior

1. Go to this page and download the library: Download shurik2k5/yii2-upload-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shurik2k5 / yii2-upload-behavior example snippets


class Document extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['file', 'file', 'extensions' => 'doc, docx, pdf', 'on' => ['insert', 'update']],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::class, [ 'id' => 'id_category' ]);
    }

    /**
     * @inheritdoc
     */
    function behaviors()
    {
        return [
            [
                'class' => \mohorev\file\UploadBehavior::class,
                'attribute' => 'file',
                'scenarios' => ['insert', 'update'],
                'path' => '@webroot/upload/docs/{category.id}',
                'url' => '@web/upload/docs/{category.id}',
            ],
        ];
    }
}

class Controller extends Controller
{
    public function actionCreate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('insert'); // Note! Set upload behavior scenario.
        
        ...
        ...
    }
}


 $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); 

$model = new Document();
$model->setScenario('update'); //Use scenarion for validation and load file
$model->uploadFromUrl('file', 'https://i.ytimg.com/vi/yfJbKba5xYM/maxresdefault.jpg');
$model->save();

$model = new Document();
$model->setScenario('update'); //Use scenarion for validation and load file
$model->uploadFromFile('file', \Yii::getAlias('@webroot/images/02.jpg'));
$model->save();

$model->getUploadUrl('file');

$model->getUploadPath('file');

class User extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['image', 'image', 'extensions' => 'jpg, jpeg, gif, png', 'on' => ['insert', 'update']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => \mohorev\file\UploadImageBehavior::class,
                'attribute' => 'image',
                'scenarios' => ['insert', 'update'],
                'placeholder' => '@app/modules/user/assets/images/userpic.jpg',
                'path' => '@webroot/upload/user/{id}',
                'url' => '@web/upload/user/{id}',
                //if need create all thumbs profiles on image upload
                'createThumbsOnSave' => true,
                //if need create thumb for one profile only on request by getThumbUploadUrl() method
                'createThumbsOnRequest' => true,
                //if you want to remove original upload file after images thumbs was generated
                'deleteOriginalFile' => true,
                'thumbs' => [
                    'thumb' => ['width' => 400, 'quality' => 90],
                    'preview' => ['width' => 200, 'height' => 200],
                    'news_thumb' => ['width' => 200, 'height' => 200, 'bg_color' => '000'],
                ],
            ],
        ];
    }
}

//remove image and all thumbs from 'photo' attribute
$model->deleteImage('photo');


/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => \mohorev\file\UploadImageBehavior::class,
            'attribute' => 'image',
            'scenarios' => ['insert', 'update'],
            'placeholder' => '@app/modules/user/assets/images/userpic.jpg',
            'path' => function ($model) {
                /** @var \app\models\UserProfile $model */
                $basePath = '@webroot/upload/profiles/';
                $path = implode('/', array_slice(str_split(md5($model->id), 2), 0, 2));
                return $basePath . $path;
            },
            'url' => function ($model) {
                /** @var \app\models\UserProfile $model */
                $baseUrl = '@web/upload/profiles/';
                $path = implode('/', array_slice(str_split(md5($model->id), 2), 0, 2));
                return $baseUrl . $path;
            },
            'thumbs' => [
                'thumb' => ['width' => 400, 'quality' => 90],
                'preview' => ['width' => 200, 'height' => 200],
                'news_thumb' => ['width' => 200, 'height' => 200, 'bg_color' => '000'],
            ],
        ],
    ];
}

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => \mohorev\file\UploadImageBehavior::class,
            'attribute' => 'image',
            'scenarios' => ['insert', 'update'],
            'placeholder' => '@app/modules/user/assets/images/userpic.jpg',
            'path' => [UserProfile::class, 'buildAvatarPath'],
            'url' => [UserProfile::class, 'buildAvatarUrl'],
            'thumbs' => [
                'thumb' => ['width' => 400, 'quality' => 90],
                'preview' => ['width' => 200, 'height' => 200],
                'news_thumb' => ['width' => 200, 'height' => 200, 'bg_color' => '000'],
            ],
        ],
    ];
}

/**
 * Define two static methos in your model for path and URL generation
 */ 
/**
 * @param \app\models\UserProfile|\yii\db\ActiveRecord $profile
 * @return string
 */
public static function buildAvatarPath(UserProfile $model)
{
    $basePath = '@webroot/upload/profiles/';
    $path = implode('/', array_slice(str_split(md5($model->id), 2), 0, 2));

    return $basePath . $path;
}

/**
 * @param \app\models\UserProfile|\yii\db\ActiveRecord $profile
 * @return string
 */
public static function buildAvatarUrl(UserProfile $model)
{
    $baseUrl = '@web/upload/profiles/';
    $path = implode('/', array_slice(str_split(md5($model->id), 2), 0, 2));

    return $baseUrl . $path;
}

 $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); 

class Track extends ActiveRecord
{
    public function getArtist()
    {
        return $this->hasOne(Artist::class, [ 'id' => 'id_artist' ]);
    }

    public function behaviors()
    {
        return [
            [
                'class' => \mohorev\file\UploadBehavior::class,
                'attribute' => 'image',
                'scenarios' => ['default'],
                'path' => '@webroot/uploads/{artist.slug}',
                'url' => '@web/uploads/{artist.slug}',
            ],
        ];
    }
}

php composer.phar