diff --git a/security/Member.php b/security/Member.php index 8dac6ff40..7be4274d0 100644 --- a/security/Member.php +++ b/security/Member.php @@ -876,6 +876,19 @@ class Member extends DataObject implements TemplateGlobalProvider { } } + /** + * Removes a member from a group. + * + * @param string $groupcode + */ + public function removeFromGroupByCode($groupcode) { + $group = Group::get()->filter(array('Code' => $groupcode))->first(); + + if($group) { + $this->Groups()->remove($group); + } + } + /** * @param Array $columns Column names on the Member record to show in {@link getTitle()}. * @param String $sep Separator diff --git a/tests/security/MemberTest.php b/tests/security/MemberTest.php index 86aa4e61c..013d54903 100644 --- a/tests/security/MemberTest.php +++ b/tests/security/MemberTest.php @@ -378,6 +378,34 @@ class MemberTest extends FunctionalTest { } + public function testRemoveFromGroupByCode() { + $grouplessMember = $this->objFromFixture('Member', 'grouplessmember'); + $memberlessGroup = $this->objFromFixture('Group','memberlessgroup'); + + $this->assertFalse($grouplessMember->Groups()->exists()); + $this->assertFalse($memberlessGroup->Members()->exists()); + + $grouplessMember->addToGroupByCode('memberless'); + + $this->assertEquals($memberlessGroup->Members()->Count(), 1); + $this->assertEquals($grouplessMember->Groups()->Count(), 1); + + $grouplessMember->addToGroupByCode('somegroupthatwouldneverexist', 'New Group'); + $this->assertEquals($grouplessMember->Groups()->Count(), 2); + + $group = DataObject::get_one('Group', "\"Code\" = 'somegroupthatwouldneverexist'"); + $this->assertNotNull($group); + $this->assertEquals($group->Code, 'somegroupthatwouldneverexist'); + $this->assertEquals($group->Title, 'New Group'); + + $grouplessMember->removeFromGroupByCode('memberless'); + $this->assertEquals($memberlessGroup->Members()->Count(), 0); + $this->assertEquals($grouplessMember->Groups()->Count(), 1); + + $grouplessMember->removeFromGroupByCode('somegroupthatwouldneverexist'); + $this->assertEquals($grouplessMember->Groups()->Count(), 0); + } + public function testInGroup() { $staffmember = $this->objFromFixture('Member', 'staffmember'); $managementmember = $this->objFromFixture('Member', 'managementmember');