/
PreviewImageField.php
90 lines (76 loc) · 2.38 KB
/
PreviewImageField.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
<?php
namespace SilverStripe\AssetAdmin\Forms;
use SilverStripe\AssetAdmin\Controller\AssetAdmin;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Folder;
use SilverStripe\Forms\FormField;
use SilverStripe\ORM\DataObject;
/**
* For providing schema data to the client side to build a preview field with upload replacement feature
*/
class PreviewImageField extends FormField
{
/**
* @var int
*/
protected $recordID = null;
protected $schemaDataType = FormField::SCHEMA_DATA_TYPE_CUSTOM;
protected $schemaComponent = 'PreviewImageField';
public function getSchemaDataDefaults()
{
$defaults = parent::getSchemaDataDefaults();
$defaults['data']['uploadFileEndpoint'] = [
'url' => AssetAdmin::singleton()->Link('api/uploadFile'),
'method' => 'post',
'payloadFormat' => 'urlencoded',
];
return $defaults;
}
public function getSchemaStateDefaults()
{
$defaults = parent::getSchemaStateDefaults();
if ($record = $this->getRecord()) {
$parent = $record->Parent();
$defaults['data'] = array_merge_recursive($defaults['data'], [
'id' => $record->ID,
'parentid' => ($parent) ? (int) $parent->ID : 0,
'url' => $record->Link(),
'version' => (int) $record->Version,
'exists' => $record->exists(),
'preview' => $record->PreviewLink(),
'category' => $record instanceof Folder ? 'folder' : $record->appCategory(),
'initialValues' => [
'FileFilename' => $record->FileFilename,
'FileHash' => $record->FileHash,
'FileVariant' => $record->FileVariant,
],
'nameField' => 'Name',
]);
}
return $defaults;
}
public function performReadonlyTransformation()
{
$this->setReadonly(true);
return $this;
}
/**
* @return File|null
*/
public function getRecord()
{
if ($this->recordID) {
return DataObject::get_by_id(File::class, $this->recordID);
}
return null;
}
/**
* @param Integer $recordID
* @return $this
*/
public function setRecordID($recordID)
{
$this->recordID = $recordID;
return $this;
}
}