Merge pull request #9014 from sminnee/fix-4142

FIX: List default items in the readonly view of ListboxField
This commit is contained in:
Guy Marriott 2019-05-27 20:13:20 +12:00 committed by GitHub
commit f97ca26e76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 0 deletions

View File

@ -276,6 +276,11 @@ abstract class MultiSelectField extends SelectField
$field->setSource($this->getSource());
$field->setReadonly(true);
// Pass through default items
if (!$this->getValueArray() && $this->getDefaultItems()) {
$field->setValue($this->getDefaultItems());
}
return $field;
}
}

View File

@ -251,4 +251,38 @@ class ListboxFieldTest extends SapphireTest
'Does not validate values not within source map'
);
}
public function testFieldWithDefaultItems()
{
$articleWithTags = $this->objFromFixture(Article::class, 'articlewithtags');
$tag1 = $this->objFromFixture(Tag::class, 'tag1');
$tag2 = $this->objFromFixture(Tag::class, 'tag2');
$tag3 = $this->objFromFixture(Tag::class, 'tag3');
$field = new ListboxField("Tags", "Test field", DataObject::get(Tag::class)->map()->toArray());
$field->setDefaultItems([$tag1->ID, $tag2->ID]);
$field->setValue(null, $articleWithTags);
$field->setDisabledItems(array($tag1->ID, $tag3->ID));
// Confirm that tag1 and tag2 are selected
$p = new CSSContentParser($field->Field());
$tag1xml = $p->getByXpath('//option[@value=' . $tag1->ID . ']');
$tag2xml = $p->getByXpath('//option[@value=' . $tag2->ID . ']');
$tag3xml = $p->getByXpath('//option[@value=' . $tag3->ID . ']');
$this->assertEquals('selected', (string)$tag1xml[0]['selected']);
$this->assertEquals('selected', (string)$tag2xml[0]['selected']);
$this->assertNull($tag3xml[0]['selected']);
// Confirm that tag1 and tag2 are listed in the readonly variation
$p = new CSSContentParser($field->performReadonlyTransformation()->Field());
$this->assertEquals(
'Tag 1, Tag 2',
trim(preg_replace('/\s+/', ' ', $p->getByXpath('//span')[0]))
);
$this->assertEquals(
'1, 2',
'' . $p->getByXpath('//input')[0]['value']
);
}
}

View File

@ -12,4 +12,8 @@ class Tag extends DataObject implements TestOnly
private static $belongs_many_many = array(
'Articles' => Article::class
);
private static $db = [
'Title' => 'Varchar',
];
}