1 | <?php |
||
2 | |||
3 | namespace Sunnysideup\CMSNiceties\Traits; |
||
4 | |||
5 | use SilverStripe\ORM\ValidationResult; |
||
6 | |||
7 | // use SilverStripe\Forms\GridField\GridFieldArchiveAction; |
||
8 | |||
9 | trait CMSNicetiesTraitForValidation |
||
10 | { |
||
11 | public function validateForUniqueValues(ValidationResult $result): ValidationResult |
||
12 | { |
||
13 | foreach ($this->Config()->get('indexes') as $index) { |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
14 | $isUniqueEntry = isset($index['type']) && 'unique' === $index['type']; |
||
15 | if ($isUniqueEntry) { |
||
16 | $fields = $index['columns'] ?? []; |
||
17 | if (count($fields) > 0) { |
||
18 | $filter = []; |
||
19 | foreach ($fields as $field) { |
||
20 | $filter[$field] = $this->{$field}; |
||
21 | } |
||
22 | |||
23 | $id = (empty($this->ID) ? 0 : $this->ID); |
||
24 | // https://stackoverflow.com/questions/63227834/return-self-for-the-return-type-of-a-function-inside-a-php-trait |
||
25 | $exists = self::get() |
||
26 | ->filter($filter) |
||
27 | ->exclude(['ID' => $id]) |
||
28 | ->exists() |
||
29 | ; |
||
30 | if ($exists) { |
||
31 | $result->addError( |
||
32 | _t( |
||
33 | self::class . '.' . $index['type'] . '_UNIQUE', |
||
34 | $index['type'] . ' needs to be unique' |
||
35 | ), |
||
36 | 'UNIQUE_' . self::class . '.' . implode('_', $fields) |
||
37 | ); |
||
38 | } |
||
39 | } |
||
40 | } |
||
41 | } |
||
42 | |||
43 | return $result; |
||
44 | } |
||
45 | } |
||
46 |