silverstripe-tagfield/src/TagField.php

481 lines
11 KiB
PHP
Raw Normal View History

2015-04-14 03:15:28 +02:00
<?php
namespace SilverStripe\TagField;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\Validator;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataObjectInterface;
use SilverStripe\ORM\SS_List;
use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements;
2015-04-14 03:15:28 +02:00
/**
2015-05-15 12:29:17 +02:00
* Provides a tagging interface, storing links between tag DataObjects and a parent DataObject.
2015-04-14 03:15:28 +02:00
*
2015-05-15 12:29:17 +02:00
* @package forms
* @subpackage fields
2015-04-14 03:15:28 +02:00
*/
2015-11-18 05:05:38 +01:00
class TagField extends DropdownField
{
/**
* @var array
*/
private static $allowed_actions = [
'suggest',
];
2015-11-18 05:05:38 +01:00
/**
* @var bool
*/
protected $shouldLazyLoad = false;
/**
* @var int
*/
protected $lazyLoadItemLimit = 10;
/**
* @var bool
*/
protected $canCreate = true;
/**
* @var string
*/
protected $titleField = 'Title';
/**
* @var DataList
*/
protected $sourceList;
2015-11-18 05:05:38 +01:00
/**
* @var bool
*/
protected $isMultiple = true;
/**
* @param string $name
* @param string $title
* @param null|DataList $source
* @param null|DataList $value
* @param string $titleField
2015-11-18 05:05:38 +01:00
*/
public function __construct($name, $title = '', $source = [], $value = null, $titleField = 'Title')
2015-11-18 05:05:38 +01:00
{
$this->setSourceList($source);
$this->setTitleField($titleField);
2015-11-18 05:05:38 +01:00
parent::__construct($name, $title, $source, $value);
}
/**
* @return bool
*/
public function getShouldLazyLoad()
{
return $this->shouldLazyLoad;
}
/**
* @param bool $shouldLazyLoad
*
* @return static
*/
public function setShouldLazyLoad($shouldLazyLoad)
{
$this->shouldLazyLoad = $shouldLazyLoad;
return $this;
}
/**
* @return int
*/
public function getLazyLoadItemLimit()
{
return $this->lazyLoadItemLimit;
}
/**
* @param int $lazyLoadItemLimit
*
* @return static
*/
public function setLazyLoadItemLimit($lazyLoadItemLimit)
{
$this->lazyLoadItemLimit = $lazyLoadItemLimit;
return $this;
}
/**
* @return bool
*/
public function getIsMultiple()
{
return $this->isMultiple;
}
/**
2015-11-18 05:05:38 +01:00
* @param bool $isMultiple
*
* @return static
*/
public function setIsMultiple($isMultiple)
{
$this->isMultiple = $isMultiple;
return $this;
}
/**
* @return bool
*/
public function getCanCreate()
{
return $this->canCreate;
}
/**
* @param bool $canCreate
*
* @return static
*/
public function setCanCreate($canCreate)
{
$this->canCreate = $canCreate;
return $this;
}
/**
* @return string
*/
public function getTitleField()
{
return $this->titleField;
}
/**
* @param string $titleField
*
* @return $this
*/
public function setTitleField($titleField)
{
$this->titleField = $titleField;
return $this;
}
/**
* Get the DataList source. The 4.x upgrade for SelectField::setSource starts to convert this to an array
* @return DataList
*/
public function getSourceList()
{
return $this->sourceList;
}
/**
* Set the model class name for tags
* @param DataList $className
* @return self
*/
public function setSourceList($sourceList)
{
$this->sourceList = $sourceList;
return $this;
}
2015-11-18 05:05:38 +01:00
/**
* {@inheritdoc}
*/
public function Field($properties = [])
2015-11-18 05:05:38 +01:00
{
$this->addExtraClass('ss-tag-field');
return $this->customise($properties)->renderWith(self::class);
}
/**
* Provide TagField data to the JSON schema for the frontend component
*
* @return array
*/
public function getSchemaDataDefaults()
{
$schema = array_merge(
parent::getSchemaDataDefaults(),
[
'name' => $this->getName() . '[]',
'lazyLoad' => $this->getShouldLazyLoad(),
'creatable' => $this->getCanCreate(),
'multi' => $this->getIsMultiple(),
'value' => $this->Value(),
'disabled' => $this->isDisabled() || $this->isReadonly(),
]
);
if (!$this->getShouldLazyLoad()) {
$schema['options'] = array_values($this->getOptions()->toNestedArray());
2018-07-16 04:34:08 +02:00
} else {
if ($this->Value()) {
$schema['value'] = $this->getOptions(true)->toNestedArray();
}
$schema['optionUrl'] = $this->getSuggestURL();
2015-11-18 05:05:38 +01:00
}
return $schema;
}
/**
* When not used in a React form factory context, this adds the schema data to SilverStripe template
* rendered attributes lists
*
* @return array
*/
public function getAttributes()
{
$attributes = parent::getAttributes();
$attributes['data-schema'] = json_encode($this->getSchemaData());
return $attributes;
2015-11-18 05:05:38 +01:00
}
/**
* @return string
*/
protected function getSuggestURL()
{
return Controller::join_links($this->Link(), 'suggest');
}
/**
* @param bool $onlySelected Only return options that are selected
2015-11-18 05:05:38 +01:00
* @return ArrayList
*/
protected function getOptions($onlySelected = false)
2015-11-18 05:05:38 +01:00
{
$source = $this->getSourceList();
2015-11-18 05:05:38 +01:00
if (!$source) {
$source = ArrayList::create();
2015-11-18 05:05:38 +01:00
}
2015-11-18 05:05:38 +01:00
$dataClass = $source->dataClass();
$titleField = $this->getTitleField();
2015-11-18 05:05:38 +01:00
$values = $this->Value();
if ($values) {
if (is_array($values)) {
$values = DataList::create($dataClass)->filter($titleField, $values);
}
2015-11-18 05:05:38 +01:00
}
if ($onlySelected) {
$source = $values;
2015-11-18 05:05:38 +01:00
}
return $source instanceof DataList ? $this->formatOptions($source) : ArrayList::create();
}
/**
* @param DataList $source
* @return ArrayList
*/
protected function formatOptions(DataList $source)
{
$options = ArrayList::create();
2015-11-18 05:05:38 +01:00
$titleField = $this->getTitleField();
foreach ($source as $object) {
2015-11-18 05:05:38 +01:00
$options->push(
ArrayData::create([
'Title' => $object->$titleField,
'Value' => $object->Title,
])
2015-11-18 05:05:38 +01:00
);
}
return $options;
}
2015-11-18 05:05:38 +01:00
/**
* {@inheritdoc}
*/
public function setValue($value, $source = null)
{
if ($source instanceof DataObject) {
$name = $this->getName();
if ($source->hasMethod($name)) {
$value = $source->$name()->column($this->getTitleField());
2015-11-18 05:05:38 +01:00
}
} elseif ($value instanceof SS_List) {
$value = $value->column($this->getTitleField());
2015-11-18 05:05:38 +01:00
}
if (!is_array($value)) {
return parent::setValue($value);
}
return parent::setValue(array_filter($value));
}
/**
* {@inheritdoc}
*/
public function saveInto(DataObjectInterface $record)
{
parent::saveInto($record);
$name = $this->getName();
$titleField = $this->getTitleField();
$values = $this->Value();
$relation = $record->$name();
$ids = [];
if (!$values) {
$values = [];
2015-11-18 05:05:38 +01:00
}
2017-01-26 06:10:14 +01:00
if (empty($record) || empty($titleField)) {
2015-11-18 05:05:38 +01:00
return;
}
if (!$record->hasMethod($name)) {
2015-11-18 05:05:38 +01:00
throw new Exception(
sprintf("%s does not have a %s method", get_class($record), $name)
);
}
foreach ($values as $key => $value) {
// Get or create record
$record = $this->getOrCreateTag($value);
if ($record) {
$ids[] = $record->ID;
$values[$key] = $record->Title;
2015-11-18 05:05:38 +01:00
}
}
$relation->setByIDList(array_filter($ids));
}
2015-11-18 05:05:38 +01:00
/**
* Get or create tag with the given value
*
* @param string $term
* @return DataObject|bool
2015-11-18 05:05:38 +01:00
*/
protected function getOrCreateTag($term)
{
// Check if existing record can be found
$source = $this->getSourceList();
2015-11-18 05:05:38 +01:00
$titleField = $this->getTitleField();
$record = $source
->filter($titleField, $term)
->first();
if ($record) {
2015-11-18 05:05:38 +01:00
return $record;
}
// Create new instance if not yet saved
2016-02-04 04:07:15 +01:00
if ($this->getCanCreate()) {
$dataClass = $source->dataClass();
$record = Injector::inst()->create($dataClass);
$record->{$titleField} = $term;
$record->write();
return $record;
}
return false;
2015-11-18 05:05:38 +01:00
}
/**
* Returns a JSON string of tags, for lazy loading.
*
* @param HTTPRequest $request
* @return HTTPResponse
2015-11-18 05:05:38 +01:00
*/
public function suggest(HTTPRequest $request)
2015-11-18 05:05:38 +01:00
{
$tags = $this->getTags($request->getVar('term'));
$response = HTTPResponse::create();
2015-11-18 05:05:38 +01:00
$response->addHeader('Content-Type', 'application/json');
$response->setBody(json_encode(['items' => $tags]));
2015-11-18 05:05:38 +01:00
return $response;
}
/**
* Returns array of arrays representing tags.
*
* @param string $term
2015-11-18 05:05:38 +01:00
* @return array
*/
protected function getTags($term)
{
$source = $this->getSourceList();
2015-11-18 05:05:38 +01:00
$titleField = $this->getTitleField();
$query = $source
->filter($titleField . ':PartialMatch:nocase', $term)
->sort($titleField)
->limit($this->getLazyLoadItemLimit());
// Map into a distinct list
$items = [];
$titleField = $this->getTitleField();
foreach ($query->map('ID', $titleField) as $id => $title) {
$items[$title] = [
'id' => $title,
'text' => $title,
];
}
return array_values($items);
2015-11-18 05:05:38 +01:00
}
/**
* DropdownField assumes value will be a scalar so we must
* override validate. This only applies to Silverstripe 3.2+
*
* @param Validator $validator
* @return bool
*/
public function validate($validator)
{
return true;
}
2016-02-25 02:32:29 +01:00
/**
* Converts the field to a readonly variant.
*
* @return ReadonlyTagField
2016-02-25 02:32:29 +01:00
*/
public function performReadonlyTransformation()
{
/** @var ReadonlyTagField $copy */
$copy = $this->castedCopy(ReadonlyTagField::class);
$copy->setSourceList($this->getSourceList());
2016-02-25 02:32:29 +01:00
return $copy;
}
/**
* Prevent the default, which would return "tag"
*
* @return string
*/
public function Type()
{
return '';
}
2015-04-14 03:15:28 +02:00
}