PHP code example of nedarta / yii2-upload-behavior

1. Go to this page and download the library: Download nedarta/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/ */

    

nedarta / yii2-upload-behavior example snippets


'aliases' => [
    '@upload' => '@webroot/upload',
],

use nedarta\behaviors\UploadBehavior;

class Event extends \yii\db\ActiveRecord
{
    public $upload; // Virtual attribute for file upload

    public function rules()
    {
        return [
            [['upload'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxSize' => 1024 * 1024 * 10],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => UploadBehavior::class,
                'uploadAttribute' => 'upload',
                'imageAttribute' => 'image',
                'uploadAlias' => '@upload/images/event',
            ],
        ];
    }
}

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

public function actionCreate()
{
    $model = new Event();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    }

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

use nedarta\behaviors\MultipleUploadBehavior;

class Event extends \yii\db\ActiveRecord
{
    public $images; // Virtual attribute receiving multiple UploadedFile instances

    public function rules()
    {
        return [
            [['images'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxFiles' => 10],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => MultipleUploadBehavior::class,
                'uploadAttribute' => 'images',
                'relatedModelClass' => EventImage::class,
                'relatedImageAttribute' => 'image',
                'relatedFkAttribute' => 'event_id', // optional: auto-derived from model name if omitted
                'uploadAlias' => '@upload/images/event',
                'variants' => [
                    '' => ['resize' => [2500, 2500]],
                    'thumb_' => ['thumbnail' => [300, 300]],
                ],
            ],
        ];
    }
}

class EventImage extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'event_image';
    }

    public function getEvent()
    {
        return $this->hasOne(Event::class, ['id' => 'event_id']);
    }
}

public function safeUp()
{
    $this->createTable('{{%event_image}}', [
        'id' => $this->primaryKey(),
        'event_id' => $this->integer()->notNull(),
        'image' => $this->string()->notNull(),
    ]);
    $this->createIndex('idx-event_image-event_id', '{{%event_image}}', 'event_id');
}

public function getEventImages()
{
    return $this->hasMany(EventImage::class, ['event_id' => 'id']);
}

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

 foreach ($model->eventImages as $image): 

'baseName' => function ($model) {
    return 'event-' . $model->id;
},

'autoRotate' => false,

'forceConvert' => 'jpg', // Converts all uploads to JPG

'variants' => [
    '' => ['resize' => [2500, 2500]],           // Original (no prefix)
    'thumb_' => ['thumbnail' => [300, 300]],    // Square thumbnail
    'medium_' => ['resize' => [800, 600]],      // Medium size
],

'variant_' => ['resize' => [1920, 1080], 'quality' => 85]

'variant_' => ['thumbnail' => [400, 400], 'quality' => 80]

'variant_' => ['smartcrop' => [600, 400], 'quality' => 85]

'variant_' => []  // Empty config = copy

'variants' => [
    '' => ['resize' => [2500, 2500]],                    // Step 1: Resize original
    'large_' => ['resize' => [1920, 1920], 'dependsOn' => ''],    // Step 2: From original
    'thumb_' => ['smartcrop' => [300, 300], 'dependsOn' => 'large_'],  // Step 3: From large
    'mini_' => ['thumbnail' => [100, 100], 'dependsOn' => 'thumb_'],   // Step 4: From thumb
],

public function behaviors()
{
    return [
        [
            'class' => UploadBehavior::class,
            'uploadAttribute' => 'upload',
            'imageAttribute' => 'image',
            'uploadAlias' => '@upload/images/blog',
            'baseName' => function ($model) {
                return Inflector::slug($model->title);
            },
            'forceConvert' => 'webp',
            'variants' => [
                '' => ['resize' => [2000, 2000]],
                'hero_' => ['resize' => [1920, 1080], 'dependsOn' => '', 'quality' => 90],
                'card_' => ['smartcrop' => [600, 400], 'dependsOn' => 'hero_'],
                'thumb_' => ['thumbnail' => [300, 200], 'dependsOn' => 'card_'],
            ],
        ],
    ];
}

'variants' => [
    '' => ['resize' => [3000, 3000]],
    'display_' => ['resize' => [1200, 1200], 'dependsOn' => ''],
    'thumb_' => ['thumbnail' => [400, 400], 'dependsOn' => 'display_'],
    'micro_' => ['thumbnail' => [150, 150], 'dependsOn' => 'thumb_'],
],

public function behaviors()
{
    return [
        [
            'class' => UploadBehavior::class,
            'uploadAttribute' => 'avatar_file',
            'imageAttribute' => 'avatar',
            'uploadAlias' => '@upload/avatars',
            'baseName' => function ($model) {
                return 'user-' . $model->id;
            },
            'forceConvert' => 'jpg',
            'variants' => [
                '' => ['thumbnail' => [800, 800]],
                'thumb_' => ['thumbnail' => [200, 200], 'dependsOn' => ''],
                'icon_' => ['thumbnail' => [64, 64], 'dependsOn' => 'thumb_'],
            ],
        ],
    ];
}

// Original
<?= Html::img('@web/upload/images/event/' . $model->image) 

public function getImageUrl($variant = '')
{
    if (empty($this->image)) {
        return null;
    }
    
    $filename = $variant . $this->image;
    return Yii::getAlias('@web/upload/images/event/' . $filename);
}

// Usage in view:
<?= Html::img($model->getImageUrl())