From 513270ca48fde1c9da520e8c4093945fff458c0b Mon Sep 17 00:00:00 2001 From: Simon Erkelens Date: Wed, 8 May 2013 19:14:21 +0300 Subject: [PATCH] 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. --- forms/FieldList.php | 14 +++++++++++--- tests/forms/FieldListTest.php | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/forms/FieldList.php b/forms/FieldList.php index d28695adb..9f4aaec6c 100644 --- a/forms/FieldList.php +++ b/forms/FieldList.php @@ -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(); diff --git a/tests/forms/FieldListTest.php b/tests/forms/FieldListTest.php index 9047623a8..8e4afc779 100644 --- a/tests/forms/FieldListTest.php +++ b/tests/forms/FieldListTest.php @@ -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. */