From a61612ec4b64131ecc9812190af95e46e179fd8d Mon Sep 17 00:00:00 2001 From: Damian Mooyman Date: Mon, 6 Jul 2020 14:17:08 +1200 Subject: [PATCH] BUG Resolve issue with react select values not being saved Fixes #150 --- src/TagField.php | 9 ++++++++- tests/TagFieldTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/TagField.php b/src/TagField.php index 34a5113..5adde7c 100644 --- a/src/TagField.php +++ b/src/TagField.php @@ -6,7 +6,6 @@ use Exception; use SilverStripe\Control\Controller; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPResponse; -use SilverStripe\Core\Convert; use SilverStripe\Core\Injector\Injector; use SilverStripe\Forms\MultiSelectField; use SilverStripe\Forms\Validator; @@ -319,6 +318,14 @@ class TagField extends MultiSelectField return parent::setValue($value); } + // Safely map php / react-select values to flat list + $values = []; + foreach ($value as $item) { + if ($item) { + $values[] = $item['Value'] ?? $item; + } + } + return parent::setValue(array_filter($value)); } diff --git a/tests/TagFieldTest.php b/tests/TagFieldTest.php index 8429e4a..3db5092 100755 --- a/tests/TagFieldTest.php +++ b/tests/TagFieldTest.php @@ -131,6 +131,30 @@ class TagFieldTest extends SapphireTest $record ); } + + public function testSavesReactTags() + { + $record = $this->getNewTagFieldTestBlogPost('BlogPost1'); + $record->write(); + + $field = new TagField('Tags', '', new DataList(TagFieldTestBlogTag::class)); + $field->setValue([ + [ + 'Title' => 'Tag1', + 'Value' => 'Tag1', + ], + [ + 'Title' => 'Tag2', + 'Value' => 'Tag2', + ], + ]); + $field->saveInto($record); + + $this->compareExpectedAndActualTags( + ['Tag1', 'Tag2'], + $record + ); + } /** * Ensure that {@see TagField::saveInto} respects existing tags