-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathImageAttachmentWidget.php
105 lines (89 loc) · 2.54 KB
/
ImageAttachmentWidget.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace zxbodya\yii2\imageAttachment;
use Yii;
use yii\base\Exception;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\helpers\Json;
use yii\helpers\Url;
/**
* Widget to provide interface for image upload to models with
* ImageAttachmentBehavior.
* @example
*
* $this->widget('ext.imageAttachment.ImageAttachmentWidget', array(
* 'model' => $model,
* 'behaviorName' => 'previewImageAttachmentBehavior',
* 'apiRoute' => 'api/saveImageAttachment',
* ));
*
* @author Bogdan Savluk <[email protected]>
*/
class ImageAttachmentWidget extends Widget
{
/**
* Route to ImageAttachmentAction
* @var string
*/
public $apiRoute;
public $assets;
/**
* Behaviour name in model to use
* @var string
*/
public $behaviorName;
/**
* Model with behaviour
* @var ActiveRecord
*/
public $model;
/**
* @return ImageAttachmentBehavior
*/
public function getAttachmentBehavior()
{
return $this->model->getBehavior($this->behaviorName);
}
public function init()
{
parent::init();
$this->registerTranslations();
}
public function registerTranslations()
{
$i18n = Yii::$app->i18n;
$i18n->translations['imageAttachment/*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => '@zxbodya/yii2/imageAttachment/messages',
'fileMap' => [
],
];
}
public function run()
{
if ($this->apiRoute === null) {
throw new Exception('$apiRoute must be set.', 500);
}
$attachmentBehavior = $this->getAttachmentBehavior();
$options = [
'hasImage' => $attachmentBehavior->hasImage(),
'previewUrl' => $attachmentBehavior->getUrl('preview'),
'previewWidth' => $attachmentBehavior->previewWidth,
'previewHeight' => $attachmentBehavior->previewHeight,
'apiUrl' => Url::to(
[
$this->apiRoute,
'type' => $attachmentBehavior->type,
'behavior' => $this->behaviorName,
'id' => $attachmentBehavior->getImageId(),
]
),
];
$optionsJS = Json::encode($options);
$view = $this->getView();
ImageAttachmentAsset::register($view);
$view->registerJs("$('#{$this->id}').imageAttachment({$optionsJS});");
return $this->render('imageAttachment');
}
}