silverstripe-tagfield/docs/en/using.md
Robbie Averill 518189e2ef SilverStripe 4 compatibility (#87)
* Update composer constraint and branch alias to support SS4 testing

* Add namespaces, update DataList quirk with getSourceList

* Add PSR-4 autoloader definition

* Move template to correct namespace location, update requirement paths

* FIX Visibility on allowed actions

* FIX Update chosen class names to match updates in framework

* Update Travis configuration for 4.x builds. Update docs for namespaced classes.

* Use "4" for the release instead of master.

* FIX Selected tag height. Move Readonly to own class.
2017-01-13 19:11:59 +00:00

2.0 KiB

Using

The primary use, for this module, is as a custom input field interface. For instance, imagine you had the following data objects:

class BlogPost extends DataObject
{
	private static $many_many = array(
		'BlogTags' => 'SilverStripe\\Blog\\Model\\BlogTag'
	);
}

class BlogTag extends DataObject
{
	private static $db = array(
		'Title' => 'Varchar(200)'
	);

	private static $belongs_many_many = array(
		'BlogPosts' => 'SilverStripe\\Blog\\Model\\BlogPost'
	);
}

If you wanted to link blog tags to blog posts, you might override getCMSFields with the following field:

$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

Note: This assumes you have imported the namespaces class, e.g. use SilverStripe\TagField\TagField;.

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.

You can also store string-based tags, for blog posts, with the following field type:

$field = StringTagField::create(
	'Tags',
	'Tags',
	array('one', 'two'),
	explode(',', $this->Tags)
);

$field->setShouldLazyLoad(true); // tags should be lazy loaded

This assumes you are storing tags in the following data object structure:

class BlogPost extends DataObject
{
	private static $db = array(
		'Tags' => 'Text'
	);
}

These tag field classes extend the DropdownField class. Their template(s) don't alter the underlying select element structure, so you can interact with them as with any normal select element. You can also interact with the Select2 instance applied to each field, as you would any other time when using Select2.

Chosen is applied to all select elements in the CMS, so this module attempts to remove it before applying Select2. Review the companion JS files to see how that happens...