TomSelectMultiField   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B saveInto() 0 28 10
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;
0 ignored issues
show
introduced by
The trait LeKoala\FormElements\TomSelect requires some properties which are not provided by LeKoala\FormElements\TomSelectMultiField: $ID, $db
Loading history...
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) {
0 ignored issues
show
introduced by
$relation is always a sub-type of SilverStripe\ORM\Relation.
Loading history...
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