2015-09-09 01:07:51 +02:00
# Using
The primary use, for this module, is as a custom input field interface. For instance, imagine you had the following data objects:
```php
2017-01-13 20:11:59 +01:00
class BlogPost extends DataObject
{
2015-09-09 01:07:51 +02:00
private static $many_many = array(
2017-01-13 20:11:59 +01:00
'BlogTags' => 'SilverStripe\\Blog\\Model\\BlogTag'
2015-09-09 01:07:51 +02:00
);
}
2017-01-13 20:11:59 +01:00
class BlogTag extends DataObject
{
2015-09-09 01:07:51 +02:00
private static $db = array(
2017-01-13 20:11:59 +01:00
'Title' => 'Varchar(200)'
2015-09-09 01:07:51 +02:00
);
private static $belongs_many_many = array(
2017-01-13 20:11:59 +01:00
'BlogPosts' => 'SilverStripe\\Blog\\Model\\BlogPost'
2015-09-09 01:07:51 +02:00
);
}
```
If you wanted to link blog tags to blog posts, you might override `getCMSFields` with the following field:
```php
$field = TagField::create(
'BlogTags',
'Blog Tags',
BlogTag::get(),
$this->BlogTags()
)
->setShouldLazyLoad(true) // tags should be lazy loaded
->setCanCreate(true); // new tag DataObjects can be created
```
2017-01-13 20:11:59 +01:00
**Note:** This assumes you have imported the namespaces class, e.g. `use SilverStripe\TagField\TagField;` .
2015-09-09 01:07:51 +02:00
This will present a tag field, in which you can select existing blog tags or create new ones. They will be created/linked after the blog posts are saved.
2018-11-15 22:15:30 +01:00
### StringTagField
You can also store string-based tags, with the following field type:
2015-09-09 01:07:51 +02:00
```php
$field = StringTagField::create(
'Tags',
'Tags',
2018-11-15 22:15:30 +01:00
['one', 'two'],
2015-09-09 01:07:51 +02:00
explode(',', $this->Tags)
2018-11-15 22:15:30 +01:00
)
->setCanCreate(true)
->setShouldLazyLoad(true);
2015-09-09 01:07:51 +02:00
```
This assumes you are storing tags in the following data object structure:
```php
2017-01-13 20:11:59 +01:00
class BlogPost extends DataObject
{
2018-11-15 22:15:30 +01:00
private static $db = [
'Tags' => 'Text',
];
2015-09-09 01:07:51 +02:00
}
```
2018-11-15 22:15:30 +01:00
In the above code example, the options available (whether lazy loaded or not) would be "one" and "two", and the
user would be able to create new options. Whichever tags are chosen would be stored in the BlogPost's `Tags` field
as a comma-delimited string.