diff --git a/src/TagField.php b/src/TagField.php index 8235961..ba5d090 100644 --- a/src/TagField.php +++ b/src/TagField.php @@ -274,11 +274,13 @@ class TagField extends MultiSelectField } // Convert an array of values into a datalist of options - if (is_array($values) && !empty($values)) { - $values = DataList::create($dataClass) - ->filter($this->getTitleField(), $values); - } else { - $values = ArrayList::create(); + if (!$values instanceof SS_List) { + if (is_array($values) && !empty($values)) { + $values = DataList::create($dataClass) + ->filter($this->getTitleField(), $values); + } else { + $values = ArrayList::create(); + } } // Prep a function to parse a dataobject into an option diff --git a/tests/TagFieldTest.php b/tests/TagFieldTest.php index 29e7441..1857aa6 100755 --- a/tests/TagFieldTest.php +++ b/tests/TagFieldTest.php @@ -360,6 +360,24 @@ class TagFieldTest extends SapphireTest $this->assertEquals('Name', $readOnlyField->getTitleField()); } + public function testItDisplaysWithSelectedValuesFromDataList() + { + $source = TagFieldTestBlogTag::get(); + $selectedTag = $source->First(); + $unselectedTag = $source->Last(); + $value = $source->filter('ID', $selectedTag->ID); // arbitrary subset + $field = new TagField('TestField', null, $source, $value); + + // Not the cleanest way to assert this, but getOptions() is protected + $schema = $field->getSchemaDataDefaults(); + $this->assertTrue( + $this->getFromOptionsByTitle($schema['options'], $selectedTag->Title)['Selected'] + ); + $this->assertFalse( + $this->getFromOptionsByTitle($schema['options'], $unselectedTag->Title)['Selected'] + ); + } + public function testGetSchemaDataDefaults() { $form = new Form(null, 'Form', new FieldList(), new FieldList()); @@ -403,4 +421,20 @@ class TagFieldTest extends SapphireTest $attributes = $field->getAttributes(); $this->assertNotEmpty($attributes['data-schema']); } + + /** + * @param array $options + * @param string $title + * @return array|null + */ + protected function getFromOptionsByTitle(array $options, $title) + { + foreach ($options as $option) { + if ($option['Title'] == $title) { + return $option; + } + } + + return null; + } }