diff --git a/readme.md b/readme.md index 4042c53..9f9e350 100644 --- a/readme.md +++ b/readme.md @@ -73,6 +73,45 @@ $field = TagField::create( **Note:** This assumes you have imported the namespaces class, e.g. use SilverStripe\TagField\TagField; + +#### Has-One Relations + +You can also use the TagField to select values for `has_one` relations. +Let's assume, that a `BlogPost` *has one* `BlogCategory`. + +```php +class BlogCategory extends DataObject +{ + private static $db = [ + 'Title' => 'Varchar(200)', + ]; +} +``` + +```php +use SilverStripe\ORM\DataObject; + +class BlogPost extends DataObject +{ + private static $has_one = [ + 'BlogCategory' => BlogCategory::class + ]; +} +``` + +```php +$field = TagField::create( + 'BlogCategoryID', + $this->fieldLabel('BlogCategory'), + BlogCategory::get() +) + ->setIsMultiple(false) + ->setCanCreate(true); +``` + +**Note:** We're using the `ID` suffix for the field-name (eg. `BlogCategoryID` instead of `BlogCategory`) and +only allow one value by setting `->setIsMultiple(false)` + ### String Tags ```php diff --git a/src/TagField.php b/src/TagField.php index 177ab23..f280634 100644 --- a/src/TagField.php +++ b/src/TagField.php @@ -402,6 +402,14 @@ class TagField extends MultiSelectField return $values->column($this->getTitleField()); } + if ($values instanceof DataObject && $values->exists()) { + return [$values->{$this->getTitleField()} ?? $values->ID]; + } + + if (is_int($values)) { + return [$values]; + } + return [trim((string) $values)]; }