Merge pull request #214 from bummzack/fix/has-one

fix: Deal with DataObjects or Int values
This commit is contained in:
Guy Sartorelli 2022-07-29 10:35:37 +12:00 committed by GitHub
commit ab1e5b2ec0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

@ -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

View File

@ -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)];
}