/** * Allows you to set groups based on a CheckboxSetField * * Pass the form element from your post data directly to this method, and * it will update the groups and add and remove the member as appropriate. * * On the form setup: * * <code> * $fields->push( * new CheckboxSetField( * "NewsletterSubscriptions", * "Receive email notification of events in ", * $sourceitems = DataObject::get("NewsletterType")->toDropDownMap("GroupID","Title"), * $selectedgroups = $member->Groups()->Map("ID","ID") * ) * ); * </code> * * On the form handler: * * <code> * $groups = $member->Groups(); * $checkboxfield = $form->Fields()->fieldByName("NewsletterSubscriptions"); * $groups->setByCheckboxSetField($checkboxfield); * </code> * * @param CheckboxSetField $checkboxsetfield The CheckboxSetField (with * data) from your form. */ function setByCheckboxSetField(CheckboxSetField $checkboxsetfield) { // Get the values from the formfield. $values = $checkboxsetfield->Value(); $sourceItems = $checkboxsetfield->getSource(); if ($sourceItems) { // If (some) values are present, add and remove as necessary. if ($values) { // update the groups based on the selections foreach ($sourceItems as $k => $item) { if (in_array($k, $values)) { $add[] = $k; } else { $remove[] = $k; } } // else we should be removing all from the necessary groups. } else { $remove = array_keys($sourceItems); } if ($add) { $this->addManyByGroupID($add); } if ($remove) { $this->RemoveManyByGroupID($remove); } } else { USER_ERROR("Member::setByCheckboxSetField() - No source items could be found for checkboxsetfield " . $checkboxsetfield->Name(), E_USER_WARNING); } }