function saveInto(DataObjectInterface $record) { $relation = $this->getRelation(); if ($relation) { $submittedTags = explode($this->getDelimiter(), $this->value); $tagClass = $this->getTagClass(); $tagLabelField = $this->getTagLabelField(); $tagObjects = DataList::create($tagClass)->filter($tagLabelField, $submittedTags); if ($tagObjects->Count() < count($submittedTags)) { // filter out the tags that exist already $tagsAsKeys = array_flip($submittedTags); foreach ($tagObjects as $tag) { $label = $tag->{$tagLabelField}; unset($tagsAsKeys[$label]); } foreach ($tagsAsKeys as $label => $value) { $tagObject = new $tagClass(); $tagObject->{$tagLabelField} = $label; $tagObject->write(); $tagObjects->add($tagObject); } } $relationList = $this->form->record->{$this->name}(); $oldTags = $relationList->map('ID', $tagLabelField)->toArray(); $relationList->removeAll(); $relationList->addMany($tagObjects->toArray()); if ($this->deleteUnusedTags) { $deletedTags = array_diff($oldTags, $tagObjects->map('ID', $tagLabelField)->toArray()); if (count($deletedTags) > 0) { $relationTable = $relation[4]; foreach ($deletedTags as $id => $title) { $query = new SQLQuery(); $query->select = array('ID', $tagLabelField); $query->from = array($relationTable); $query->where = array("ID = " . $id); $count = $query->Count(); if ($count == 0) { DataObject::delete_by_id($tagClass, $id); } } } } } else { if ($record->hasField($this->name)) { $record->setCastedField($this->name, $this->dataValue()); } else { // @TODO: better error handling } } }