1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LeKoala\FormElements; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use SilverStripe\ORM\Relation; |
7
|
|
|
use SilverStripe\ORM\DataObject; |
8
|
|
|
use SilverStripe\Forms\ListboxField; |
9
|
|
|
use SilverStripe\ORM\DataObjectInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @link https://tom-select.js.org/ |
13
|
|
|
*/ |
14
|
|
|
class TomSelectMultiField extends ListboxField implements AjaxPoweredField, LocalizableField, TagsField |
15
|
|
|
{ |
16
|
|
|
use TomSelect; |
|
|
|
|
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param DataObject|DataObjectInterface $record The record to save into |
20
|
|
|
*/ |
21
|
|
|
public function saveInto(DataObjectInterface $record) |
22
|
|
|
{ |
23
|
|
|
$fieldName = $this->getName(); |
24
|
|
|
if (empty($fieldName) || empty($record)) { |
25
|
|
|
return; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** @var Relation $relation */ |
29
|
|
|
$relation = $record->hasMethod($fieldName) ? $record->$fieldName() : null; |
30
|
|
|
|
31
|
|
|
// Detect DB relation or field |
32
|
|
|
$items = $this->getValueArray(); |
33
|
|
|
if ($relation && $relation instanceof Relation) { |
|
|
|
|
34
|
|
|
foreach ($items as $idx => $item) { |
35
|
|
|
// If the item is a string, it's not an ID and needs to be created |
36
|
|
|
if (!is_numeric($item)) { |
37
|
|
|
$cb = $this->onNewTag; |
38
|
|
|
if (!$cb) { |
39
|
|
|
throw new Exception("Please define a onNewTag callback"); |
40
|
|
|
} |
41
|
|
|
$items[$idx] = $cb($item); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
// Save ids into relation |
45
|
|
|
$relation->setByIDList(array_values($items)); |
46
|
|
|
} elseif ($record->hasField($fieldName)) { |
47
|
|
|
// Save dataValue into field |
48
|
|
|
$record->$fieldName = $this->stringEncode($items); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|