API: Allow array of fields passed to FieldList::removeByName()

Supports passing an array to removeByName(), which is iterate and then removed. Useful for removing fields from a fieldlist that are not on a tab. Similar to removeFieldsFromTab();
This is cleaner than a new function.
This commit is contained in:
Simon Erkelens 2013-05-08 19:14:21 +03:00 committed by Sam Minnee
parent eedcacb256
commit 513270ca48
2 changed files with 31 additions and 3 deletions

View File

@ -170,10 +170,10 @@ class FieldList extends ArrayList {
}
/**
* Remove a field from this FieldList by Name.
* Remove a field or fields from this FieldList by Name.
* The field could also be inside a CompositeField.
*
* @param string $fieldName The name of the field or tab
* @param string|array $fieldName The name of, or an array with the field(s) or tab(s)
* @param boolean $dataFieldOnly If this is true, then a field will only
* be removed if it's a data field. Dataless fields, such as tabs, will
* be left as-is.
@ -182,8 +182,16 @@ class FieldList extends ArrayList {
if(!$fieldName) {
user_error('FieldList::removeByName() was called with a blank field name.', E_USER_WARNING);
}
// Handle array syntax
if(is_array($fieldName)) {
foreach($fieldName as $field){
$this->removeByName($field, $dataFieldOnly);
}
return;
}
$this->flushFieldsCache();
foreach($this->items as $i => $child) {
if(is_object($child)){
$childName = $child->getName();

View File

@ -146,6 +146,26 @@ class FieldListTest extends SapphireTest {
$this->assertEquals(0, $fields->Count());
}
/**
* Test removing multiple fields from a set by their names in an array.
*/
public function testRemoveFieldsByName() {
$fields = new FieldList();
/* First of all, we add some fields into our FieldList object */
$fields->push(new TextField('Name', 'Your name'));
$fields->push(new TextField('Email', 'Your email'));
/* We have 2 fields in our set now */
$this->assertEquals(2, $fields->Count());
/* Then, we call up removeByName() to take it out again */
$fields->removeByName(array('Name', 'Email'));
/* We have 0 fields in our set now, as we've just removed the one we added */
$this->assertEquals(0, $fields->Count());
}
/**
* Test replacing a field with another one.
*/