SelectedColourPickerFormFieldDropdown::validate()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Sunnysideup\SelectedColourPicker\Forms;
4
5
use SilverStripe\Forms\DropdownField;
6
use SilverStripe\Forms\Validator;
7
use SilverStripe\ORM\FieldType\DBField;
8
use Sunnysideup\SelectedColourPicker\ViewableData\SelectedColourPickerFormFieldSwatches;
9
10
class SelectedColourPickerFormFieldDropdown extends DropdownField
11
{
12
13
    protected $limitedToOptions = true;
14
15
    protected $isBgColour = true;
16
17
    public function setLimitedToOptions(bool $bool)
18
    {
19
        $this->limitedToOptions = $bool;
20
21
        return $this;
22
    }
23
24
    public function setIsBgColour(bool $bool)
25
    {
26
        $this->isBgColour = $bool;
27
28
        return $this;
29
    }
30
31
    /**
32
     * Validate this field.
33
     *
34
     * @param Validator $validator
35
     *
36
     * @return bool
37
     */
38
    public function validate($validator)
39
    {
40
        if ($this->limitedToOptions && $this->value && ! isset($this->source[$this->value])) {
41
            $validator->validationError(
42
                $this->name,
43
                'Please selected from suggested options only',
44
                'validation'
45
            );
46
47
            return false;
48
        }
49
50
        return true;
51
    }
52
53
    public function Field($properties = [])
54
    {
55
        $this->setDescription(
56
            DBField::create_field(
57
                'HTMLText',
58
                SelectedColourPickerFormFieldSwatches::get_swatches_html(
59
                    $this->name,
60
                    $this->value,
61
                    $this->getListMap($this->source),
62
                    (bool) $this->isBgColour
63
                )
64
            )
65
        );
66
67
        return parent::Field();
68
    }
69
}
70