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',
],
];
}
}
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']);
}