Completed
Pull Request — master (#113)
by
unknown
02:49
created
src/ReadonlyTagField.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -12,29 +12,29 @@
 block discarded – undo
12 12
  */
13 13
 class ReadonlyTagField extends TagField
14 14
 {
15
-    /**
16
-     * {@inheritDoc}
17
-     */
18
-    protected $readonly = true;
15
+	/**
16
+	 * {@inheritDoc}
17
+	 */
18
+	protected $readonly = true;
19 19
 
20
-    /**
21
-     * Render the readonly field as HTML.
22
-     *
23
-     * @param array $properties
24
-     * @return HTMLText
25
-     */
26
-    public function Field($properties = array())
27
-    {
28
-        $options = array();
20
+	/**
21
+	 * Render the readonly field as HTML.
22
+	 *
23
+	 * @param array $properties
24
+	 * @return HTMLText
25
+	 */
26
+	public function Field($properties = array())
27
+	{
28
+		$options = array();
29 29
 
30
-        foreach ($this->getOptions()->filter('Selected', true) as $option) {
31
-            $options[] = $option->Title;
32
-        }
30
+		foreach ($this->getOptions()->filter('Selected', true) as $option) {
31
+			$options[] = $option->Title;
32
+		}
33 33
 
34
-        $field = ReadonlyField::create($this->name . '_Readonly', $this->title);
34
+		$field = ReadonlyField::create($this->name . '_Readonly', $this->title);
35 35
 
36
-        $field->setForm($this->form);
37
-        $field->setValue(implode(', ', $options));
38
-        return $field->Field();
39
-    }
36
+		$field->setForm($this->form);
37
+		$field->setValue(implode(', ', $options));
38
+		return $field->Field();
39
+	}
40 40
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
             $options[] = $option->Title;
32 32
         }
33 33
 
34
-        $field = ReadonlyField::create($this->name . '_Readonly', $this->title);
34
+        $field = ReadonlyField::create($this->name.'_Readonly', $this->title);
35 35
 
36 36
         $field->setForm($this->form);
37 37
         $field->setValue(implode(', ', $options));
Please login to merge, or discard this patch.
src/StringTagField.php 2 patches
Indentation   +343 added lines, -343 removed lines patch added patch discarded remove patch
@@ -25,348 +25,348 @@
 block discarded – undo
25 25
  */
26 26
 class StringTagField extends DropdownField
27 27
 {
28
-    /**
29
-     * @var array
30
-     */
31
-    private static $allowed_actions = [
32
-        'suggest'
33
-    ];
34
-
35
-    /**
36
-     * @var bool
37
-     */
38
-    protected $shouldLazyLoad = false;
39
-
40
-    /**
41
-     * @var int
42
-     */
43
-    protected $lazyLoadItemLimit = 10;
44
-
45
-    /**
46
-     * @var bool
47
-     */
48
-    protected $canCreate = true;
49
-
50
-    /**
51
-     * @var null|DataObject
52
-     */
53
-    protected $record;
54
-
55
-    /**
56
-     * @var bool
57
-     */
58
-    protected $isMultiple = true;
59
-
60
-    /**
61
-     * @return bool
62
-     */
63
-    public function getShouldLazyLoad()
64
-    {
65
-        return $this->shouldLazyLoad;
66
-    }
67
-
68
-    /**
69
-     * @param bool $shouldLazyLoad
70
-     *
71
-     * @return static
72
-     */
73
-    public function setShouldLazyLoad($shouldLazyLoad)
74
-    {
75
-        $this->shouldLazyLoad = $shouldLazyLoad;
76
-
77
-        return $this;
78
-    }
79
-
80
-    /**
81
-     * @return int
82
-     */
83
-    public function getLazyLoadItemLimit()
84
-    {
85
-        return $this->lazyLoadItemLimit;
86
-    }
87
-
88
-    /**
89
-     * @param int $lazyLoadItemLimit
90
-     *
91
-     * @return static
92
-     */
93
-    public function setLazyLoadItemLimit($lazyLoadItemLimit)
94
-    {
95
-        $this->lazyLoadItemLimit = $lazyLoadItemLimit;
96
-
97
-        return $this;
98
-    }
99
-
100
-    /**
101
-     * @return bool
102
-     */
103
-    public function getIsMultiple()
104
-    {
105
-        return $this->isMultiple;
106
-    }
107
-
108
-    /**
109
-     * @param bool $isMultiple
110
-     *
111
-     * @return static
112
-     */
113
-    public function setIsMultiple($isMultiple)
114
-    {
115
-        $this->isMultiple = $isMultiple;
116
-
117
-        return $this;
118
-    }
119
-
120
-    /**
121
-     * @return null|DataObject
122
-     */
123
-    public function getRecord()
124
-    {
125
-        if ($this->record) {
126
-            return $this->record;
127
-        }
128
-
129
-        if ($form = $this->getForm()) {
130
-            return $form->getRecord();
131
-        }
132
-
133
-        return null;
134
-    }
135
-
136
-    /**
137
-     * @param DataObject $record
138
-     *
139
-     * @return $this
140
-     */
141
-    public function setRecord(DataObject $record)
142
-    {
143
-        $this->record = $record;
144
-
145
-        return $this;
146
-    }
147
-
148
-    /**
149
-     * {@inheritdoc}
150
-     */
151
-    public function Field($properties = array())
152
-    {
153
-        Requirements::css('silverstripe/tagfield:css/select2.min.css');
154
-        Requirements::css('silverstripe/tagfield:css/TagField.css');
155
-
156
-        Requirements::javascript('silverstripe/tagfield:js/select2.js');
157
-        Requirements::javascript('silverstripe/tagfield:js/TagField.js');
158
-
159
-        $this->addExtraClass('ss-tag-field');
160
-
161
-        if ($this->getIsMultiple()) {
162
-            $this->setAttribute('multiple', 'multiple');
163
-        }
164
-
165
-        if ($this->getShouldLazyLoad()) {
166
-            $this->setAttribute('data-ss-tag-field-suggest-url', $this->getSuggestURL());
167
-        } else {
168
-            $properties = array_merge($properties, array(
169
-                'Options' => $this->getOptions()
170
-            ));
171
-        }
172
-
173
-        $this->setAttribute('data-can-create', (int) $this->getCanCreate());
174
-
175
-        return $this
176
-            ->customise($properties)
177
-            ->renderWith(TagField::class);
178
-    }
179
-
180
-    /**
181
-     * @return string
182
-     */
183
-    protected function getSuggestURL()
184
-    {
185
-        return Controller::join_links($this->Link(), 'suggest');
186
-    }
187
-
188
-    /**
189
-     * @return ArrayList
190
-     */
191
-    protected function getOptions()
192
-    {
193
-        $options = ArrayList::create();
194
-
195
-        $source = $this->getSource();
196
-
197
-        if ($source instanceof Iterator) {
198
-            $source = iterator_to_array($source);
199
-        }
200
-
201
-        $values = $this->Value();
202
-
203
-        foreach ($source as $value) {
204
-            $options->push(
205
-                ArrayData::create(array(
206
-                    'Title' => $value,
207
-                    'Value' => $value,
208
-                    'Selected' => in_array($value, $values),
209
-                ))
210
-            );
211
-        }
212
-
213
-        return $options;
214
-    }
215
-
216
-    /**
217
-     * {@inheritdoc}
218
-     */
219
-    public function setValue($value, $source = null)
220
-    {
221
-        if (is_string($value)) {
222
-            $value = explode(',', $value);
223
-        }
224
-
225
-        if ($source instanceof DataObject) {
226
-            $name = $this->getName();
227
-            $value = explode(',', $source->$name);
228
-        }
229
-
230
-        if ($source instanceof SS_List) {
231
-            $value = $source->column('ID');
232
-        }
233
-
234
-        if (is_null($value)) {
235
-            $value = array();
236
-        }
237
-
238
-        return parent::setValue(array_filter($value));
239
-    }
240
-
241
-    /**
242
-     * {@inheritdoc}
243
-     */
244
-    public function getAttributes()
245
-    {
246
-        return array_merge(
247
-            parent::getAttributes(),
248
-            array('name' => $this->getName() . '[]')
249
-        );
250
-    }
251
-
252
-    /**
253
-     * {@inheritdoc}
254
-     */
255
-    public function saveInto(DataObjectInterface $record)
256
-    {
257
-        parent::saveInto($record);
258
-
259
-        $name = $this->getName();
260
-
261
-        $record->$name = join(',', $this->Value());
262
-        $record->write();
263
-    }
264
-
265
-    /**
266
-     * Returns a JSON string of tags, for lazy loading.
267
-     *
268
-     * @param  HTTPRequest $request
269
-     * @return HTTPResponse
270
-     */
271
-    public function suggest(HTTPRequest $request)
272
-    {
273
-        $responseBody = Convert::raw2json(
274
-            array('items' => array())
275
-        );
276
-
277
-        $response = new HTTPResponse;
278
-        $response->addHeader('Content-Type', 'application/json');
279
-
280
-        if ($record = $this->getRecord()) {
281
-            $tags = array();
282
-            $term = $request->getVar('term');
283
-
284
-            if ($record->hasField($this->getName())) {
285
-                $tags = $this->getTags($term);
286
-            }
287
-
288
-            $responseBody = Convert::raw2json(
289
-                array('items' => $tags)
290
-            );
291
-        }
292
-
293
-        $response->setBody($responseBody);
294
-
295
-        return $response;
296
-    }
297
-
298
-    /**
299
-     * Returns array of arrays representing tags.
300
-     *
301
-     * @param string $term
302
-     *
303
-     * @return array
304
-     */
305
-    protected function getTags($term)
306
-    {
307
-        $record = $this->getRecord();
308
-
309
-        if (!$record) {
310
-            return array();
311
-        }
312
-
313
-        $fieldName = $this->getName();
314
-        $className = $record->getClassName();
315
-
316
-        $term = Convert::raw2sql($term);
317
-
318
-        $query = $className::get()
319
-            ->filter($fieldName . ':PartialMatch:nocase', $term)
320
-            ->limit($this->getLazyLoadItemLimit());
321
-
322
-        $items = array();
323
-
324
-        foreach ($query->column($fieldName) as $tags) {
325
-            $tags = explode(',', $tags);
326
-
327
-            foreach ($tags as $i => $tag) {
328
-                if (stripos($tag, $term) !== false && !in_array($tag, $items)) {
329
-                    $items[] = array(
330
-                        'id' => $tag,
331
-                        'text' => $tag
332
-                    );
333
-                }
334
-            }
335
-        }
336
-
337
-        return $items;
338
-    }
339
-
340
-    /**
341
-     * DropdownField assumes value will be a scalar so we must
342
-     * override validate. This only applies to Silverstripe 3.2+
343
-     *
344
-     * @param Validator $validator
345
-     * @return bool
346
-     */
347
-    public function validate($validator)
348
-    {
349
-        return true;
350
-    }
351
-
352
-    /**
353
-     * @return bool
354
-     */
355
-    public function getCanCreate()
356
-    {
357
-        return $this->canCreate;
358
-    }
359
-
360
-    /**
361
-     * @param bool $canCreate
362
-     *
363
-     * @return static
364
-     */
365
-    public function setCanCreate($canCreate)
366
-    {
367
-        $this->canCreate = $canCreate;
368
-
369
-        return $this;
370
-    }
28
+	/**
29
+	 * @var array
30
+	 */
31
+	private static $allowed_actions = [
32
+		'suggest'
33
+	];
34
+
35
+	/**
36
+	 * @var bool
37
+	 */
38
+	protected $shouldLazyLoad = false;
39
+
40
+	/**
41
+	 * @var int
42
+	 */
43
+	protected $lazyLoadItemLimit = 10;
44
+
45
+	/**
46
+	 * @var bool
47
+	 */
48
+	protected $canCreate = true;
49
+
50
+	/**
51
+	 * @var null|DataObject
52
+	 */
53
+	protected $record;
54
+
55
+	/**
56
+	 * @var bool
57
+	 */
58
+	protected $isMultiple = true;
59
+
60
+	/**
61
+	 * @return bool
62
+	 */
63
+	public function getShouldLazyLoad()
64
+	{
65
+		return $this->shouldLazyLoad;
66
+	}
67
+
68
+	/**
69
+	 * @param bool $shouldLazyLoad
70
+	 *
71
+	 * @return static
72
+	 */
73
+	public function setShouldLazyLoad($shouldLazyLoad)
74
+	{
75
+		$this->shouldLazyLoad = $shouldLazyLoad;
76
+
77
+		return $this;
78
+	}
79
+
80
+	/**
81
+	 * @return int
82
+	 */
83
+	public function getLazyLoadItemLimit()
84
+	{
85
+		return $this->lazyLoadItemLimit;
86
+	}
87
+
88
+	/**
89
+	 * @param int $lazyLoadItemLimit
90
+	 *
91
+	 * @return static
92
+	 */
93
+	public function setLazyLoadItemLimit($lazyLoadItemLimit)
94
+	{
95
+		$this->lazyLoadItemLimit = $lazyLoadItemLimit;
96
+
97
+		return $this;
98
+	}
99
+
100
+	/**
101
+	 * @return bool
102
+	 */
103
+	public function getIsMultiple()
104
+	{
105
+		return $this->isMultiple;
106
+	}
107
+
108
+	/**
109
+	 * @param bool $isMultiple
110
+	 *
111
+	 * @return static
112
+	 */
113
+	public function setIsMultiple($isMultiple)
114
+	{
115
+		$this->isMultiple = $isMultiple;
116
+
117
+		return $this;
118
+	}
119
+
120
+	/**
121
+	 * @return null|DataObject
122
+	 */
123
+	public function getRecord()
124
+	{
125
+		if ($this->record) {
126
+			return $this->record;
127
+		}
128
+
129
+		if ($form = $this->getForm()) {
130
+			return $form->getRecord();
131
+		}
132
+
133
+		return null;
134
+	}
135
+
136
+	/**
137
+	 * @param DataObject $record
138
+	 *
139
+	 * @return $this
140
+	 */
141
+	public function setRecord(DataObject $record)
142
+	{
143
+		$this->record = $record;
144
+
145
+		return $this;
146
+	}
147
+
148
+	/**
149
+	 * {@inheritdoc}
150
+	 */
151
+	public function Field($properties = array())
152
+	{
153
+		Requirements::css('silverstripe/tagfield:css/select2.min.css');
154
+		Requirements::css('silverstripe/tagfield:css/TagField.css');
155
+
156
+		Requirements::javascript('silverstripe/tagfield:js/select2.js');
157
+		Requirements::javascript('silverstripe/tagfield:js/TagField.js');
158
+
159
+		$this->addExtraClass('ss-tag-field');
160
+
161
+		if ($this->getIsMultiple()) {
162
+			$this->setAttribute('multiple', 'multiple');
163
+		}
164
+
165
+		if ($this->getShouldLazyLoad()) {
166
+			$this->setAttribute('data-ss-tag-field-suggest-url', $this->getSuggestURL());
167
+		} else {
168
+			$properties = array_merge($properties, array(
169
+				'Options' => $this->getOptions()
170
+			));
171
+		}
172
+
173
+		$this->setAttribute('data-can-create', (int) $this->getCanCreate());
174
+
175
+		return $this
176
+			->customise($properties)
177
+			->renderWith(TagField::class);
178
+	}
179
+
180
+	/**
181
+	 * @return string
182
+	 */
183
+	protected function getSuggestURL()
184
+	{
185
+		return Controller::join_links($this->Link(), 'suggest');
186
+	}
187
+
188
+	/**
189
+	 * @return ArrayList
190
+	 */
191
+	protected function getOptions()
192
+	{
193
+		$options = ArrayList::create();
194
+
195
+		$source = $this->getSource();
196
+
197
+		if ($source instanceof Iterator) {
198
+			$source = iterator_to_array($source);
199
+		}
200
+
201
+		$values = $this->Value();
202
+
203
+		foreach ($source as $value) {
204
+			$options->push(
205
+				ArrayData::create(array(
206
+					'Title' => $value,
207
+					'Value' => $value,
208
+					'Selected' => in_array($value, $values),
209
+				))
210
+			);
211
+		}
212
+
213
+		return $options;
214
+	}
215
+
216
+	/**
217
+	 * {@inheritdoc}
218
+	 */
219
+	public function setValue($value, $source = null)
220
+	{
221
+		if (is_string($value)) {
222
+			$value = explode(',', $value);
223
+		}
224
+
225
+		if ($source instanceof DataObject) {
226
+			$name = $this->getName();
227
+			$value = explode(',', $source->$name);
228
+		}
229
+
230
+		if ($source instanceof SS_List) {
231
+			$value = $source->column('ID');
232
+		}
233
+
234
+		if (is_null($value)) {
235
+			$value = array();
236
+		}
237
+
238
+		return parent::setValue(array_filter($value));
239
+	}
240
+
241
+	/**
242
+	 * {@inheritdoc}
243
+	 */
244
+	public function getAttributes()
245
+	{
246
+		return array_merge(
247
+			parent::getAttributes(),
248
+			array('name' => $this->getName() . '[]')
249
+		);
250
+	}
251
+
252
+	/**
253
+	 * {@inheritdoc}
254
+	 */
255
+	public function saveInto(DataObjectInterface $record)
256
+	{
257
+		parent::saveInto($record);
258
+
259
+		$name = $this->getName();
260
+
261
+		$record->$name = join(',', $this->Value());
262
+		$record->write();
263
+	}
264
+
265
+	/**
266
+	 * Returns a JSON string of tags, for lazy loading.
267
+	 *
268
+	 * @param  HTTPRequest $request
269
+	 * @return HTTPResponse
270
+	 */
271
+	public function suggest(HTTPRequest $request)
272
+	{
273
+		$responseBody = Convert::raw2json(
274
+			array('items' => array())
275
+		);
276
+
277
+		$response = new HTTPResponse;
278
+		$response->addHeader('Content-Type', 'application/json');
279
+
280
+		if ($record = $this->getRecord()) {
281
+			$tags = array();
282
+			$term = $request->getVar('term');
283
+
284
+			if ($record->hasField($this->getName())) {
285
+				$tags = $this->getTags($term);
286
+			}
287
+
288
+			$responseBody = Convert::raw2json(
289
+				array('items' => $tags)
290
+			);
291
+		}
292
+
293
+		$response->setBody($responseBody);
294
+
295
+		return $response;
296
+	}
297
+
298
+	/**
299
+	 * Returns array of arrays representing tags.
300
+	 *
301
+	 * @param string $term
302
+	 *
303
+	 * @return array
304
+	 */
305
+	protected function getTags($term)
306
+	{
307
+		$record = $this->getRecord();
308
+
309
+		if (!$record) {
310
+			return array();
311
+		}
312
+
313
+		$fieldName = $this->getName();
314
+		$className = $record->getClassName();
315
+
316
+		$term = Convert::raw2sql($term);
317
+
318
+		$query = $className::get()
319
+			->filter($fieldName . ':PartialMatch:nocase', $term)
320
+			->limit($this->getLazyLoadItemLimit());
321
+
322
+		$items = array();
323
+
324
+		foreach ($query->column($fieldName) as $tags) {
325
+			$tags = explode(',', $tags);
326
+
327
+			foreach ($tags as $i => $tag) {
328
+				if (stripos($tag, $term) !== false && !in_array($tag, $items)) {
329
+					$items[] = array(
330
+						'id' => $tag,
331
+						'text' => $tag
332
+					);
333
+				}
334
+			}
335
+		}
336
+
337
+		return $items;
338
+	}
339
+
340
+	/**
341
+	 * DropdownField assumes value will be a scalar so we must
342
+	 * override validate. This only applies to Silverstripe 3.2+
343
+	 *
344
+	 * @param Validator $validator
345
+	 * @return bool
346
+	 */
347
+	public function validate($validator)
348
+	{
349
+		return true;
350
+	}
351
+
352
+	/**
353
+	 * @return bool
354
+	 */
355
+	public function getCanCreate()
356
+	{
357
+		return $this->canCreate;
358
+	}
359
+
360
+	/**
361
+	 * @param bool $canCreate
362
+	 *
363
+	 * @return static
364
+	 */
365
+	public function setCanCreate($canCreate)
366
+	{
367
+		$this->canCreate = $canCreate;
368
+
369
+		return $this;
370
+	}
371 371
     
372 372
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
     {
246 246
         return array_merge(
247 247
             parent::getAttributes(),
248
-            array('name' => $this->getName() . '[]')
248
+            array('name' => $this->getName().'[]')
249 249
         );
250 250
     }
251 251
 
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
         $term = Convert::raw2sql($term);
317 317
 
318 318
         $query = $className::get()
319
-            ->filter($fieldName . ':PartialMatch:nocase', $term)
319
+            ->filter($fieldName.':PartialMatch:nocase', $term)
320 320
             ->limit($this->getLazyLoadItemLimit());
321 321
 
322 322
         $items = array();
Please login to merge, or discard this patch.
tests/StringTagFieldTest.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -12,112 +12,112 @@
 block discarded – undo
12 12
  */
13 13
 class StringTagFieldTest extends SapphireTest
14 14
 {
15
-    /**
16
-     * @var string
17
-     */
18
-    protected static $fixture_file = 'StringTagFieldTest.yml';
19
-
20
-    /**
21
-     * @var array
22
-     */
23
-    protected static $extra_dataobjects = array(
24
-        StringTagFieldTestBlogPost::class,
25
-    );
26
-
27
-    public function testItSavesTagsOnNewRecords()
28
-    {
29
-        $record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
30
-
31
-        $field = new StringTagField('Tags');
32
-        $field->setValue(array('Tag1', 'Tag2'));
33
-        $field->saveInto($record);
34
-
35
-        $record->write();
36
-
37
-        $this->assertEquals('Tag1,Tag2', $record->Tags);
38
-    }
39
-
40
-    /**
41
-     * @param string $name
42
-     *
43
-     * @return StringTagFieldTestBlogPost
44
-     */
45
-    protected function getNewStringTagFieldTestBlogPost($name)
46
-    {
47
-        return $this->objFromFixture(
48
-            StringTagFieldTestBlogPost::class,
49
-            $name
50
-        );
51
-    }
52
-
53
-    public function testItSavesTagsOnExistingRecords()
54
-    {
55
-        $record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
56
-        $record->write();
57
-
58
-        $field = new StringTagField('Tags');
59
-        $field->setValue(array('Tag1', 'Tag2'));
60
-        $field->saveInto($record);
61
-
62
-        $this->assertEquals('Tag1,Tag2', $record->Tags);
63
-    }
64
-
65
-    public function testItSuggestsTags()
66
-    {
67
-        $record = $this->getNewStringTagFieldTestBlogPost('BlogPost2');
68
-
69
-        $field = new StringTagField('Tags');
70
-        $field->setRecord($record);
71
-
72
-        /**
73
-         * Partial tag title match.
74
-         */
75
-        $request = $this->getNewRequest(array('term' => 'Tag'));
76
-
77
-        $this->assertEquals(
78
-            '{"items":[{"id":"Tag1","text":"Tag1"},{"id":"Tag2","text":"Tag2"}]}',
79
-            $field->suggest($request)->getBody()
80
-        );
81
-
82
-        /**
83
-         * Exact tag title match.
84
-         */
85
-        $request = $this->getNewRequest(array('term' => 'Tag1'));
86
-
87
-        $this->assertEquals($field->suggest($request)->getBody(), '{"items":[{"id":"Tag1","text":"Tag1"}]}');
88
-
89
-        /**
90
-         * Case-insensitive tag title match.
91
-         */
92
-        $request = $this->getNewRequest(array('term' => 'TAG1'));
93
-
94
-        $this->assertEquals(
95
-            '{"items":[{"id":"Tag1","text":"Tag1"}]}',
96
-            $field->suggest($request)->getBody()
97
-        );
98
-
99
-        /**
100
-         * No tag title match.
101
-         */
102
-        $request = $this->getNewRequest(array('term' => 'unknown'));
103
-
104
-        $this->assertEquals(
105
-            '{"items":[]}',
106
-            $field->suggest($request)->getBody()
107
-        );
108
-    }
109
-
110
-    /**
111
-     * @param array $parameters
112
-     *
113
-     * @return HTTPRequest
114
-     */
115
-    protected function getNewRequest(array $parameters)
116
-    {
117
-        return new HTTPRequest(
118
-            'get',
119
-            'StringTagFieldTestController/StringTagFieldTestForm/fields/Tags/suggest',
120
-            $parameters
121
-        );
122
-    }
15
+	/**
16
+	 * @var string
17
+	 */
18
+	protected static $fixture_file = 'StringTagFieldTest.yml';
19
+
20
+	/**
21
+	 * @var array
22
+	 */
23
+	protected static $extra_dataobjects = array(
24
+		StringTagFieldTestBlogPost::class,
25
+	);
26
+
27
+	public function testItSavesTagsOnNewRecords()
28
+	{
29
+		$record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
30
+
31
+		$field = new StringTagField('Tags');
32
+		$field->setValue(array('Tag1', 'Tag2'));
33
+		$field->saveInto($record);
34
+
35
+		$record->write();
36
+
37
+		$this->assertEquals('Tag1,Tag2', $record->Tags);
38
+	}
39
+
40
+	/**
41
+	 * @param string $name
42
+	 *
43
+	 * @return StringTagFieldTestBlogPost
44
+	 */
45
+	protected function getNewStringTagFieldTestBlogPost($name)
46
+	{
47
+		return $this->objFromFixture(
48
+			StringTagFieldTestBlogPost::class,
49
+			$name
50
+		);
51
+	}
52
+
53
+	public function testItSavesTagsOnExistingRecords()
54
+	{
55
+		$record = $this->getNewStringTagFieldTestBlogPost('BlogPost1');
56
+		$record->write();
57
+
58
+		$field = new StringTagField('Tags');
59
+		$field->setValue(array('Tag1', 'Tag2'));
60
+		$field->saveInto($record);
61
+
62
+		$this->assertEquals('Tag1,Tag2', $record->Tags);
63
+	}
64
+
65
+	public function testItSuggestsTags()
66
+	{
67
+		$record = $this->getNewStringTagFieldTestBlogPost('BlogPost2');
68
+
69
+		$field = new StringTagField('Tags');
70
+		$field->setRecord($record);
71
+
72
+		/**
73
+		 * Partial tag title match.
74
+		 */
75
+		$request = $this->getNewRequest(array('term' => 'Tag'));
76
+
77
+		$this->assertEquals(
78
+			'{"items":[{"id":"Tag1","text":"Tag1"},{"id":"Tag2","text":"Tag2"}]}',
79
+			$field->suggest($request)->getBody()
80
+		);
81
+
82
+		/**
83
+		 * Exact tag title match.
84
+		 */
85
+		$request = $this->getNewRequest(array('term' => 'Tag1'));
86
+
87
+		$this->assertEquals($field->suggest($request)->getBody(), '{"items":[{"id":"Tag1","text":"Tag1"}]}');
88
+
89
+		/**
90
+		 * Case-insensitive tag title match.
91
+		 */
92
+		$request = $this->getNewRequest(array('term' => 'TAG1'));
93
+
94
+		$this->assertEquals(
95
+			'{"items":[{"id":"Tag1","text":"Tag1"}]}',
96
+			$field->suggest($request)->getBody()
97
+		);
98
+
99
+		/**
100
+		 * No tag title match.
101
+		 */
102
+		$request = $this->getNewRequest(array('term' => 'unknown'));
103
+
104
+		$this->assertEquals(
105
+			'{"items":[]}',
106
+			$field->suggest($request)->getBody()
107
+		);
108
+	}
109
+
110
+	/**
111
+	 * @param array $parameters
112
+	 *
113
+	 * @return HTTPRequest
114
+	 */
115
+	protected function getNewRequest(array $parameters)
116
+	{
117
+		return new HTTPRequest(
118
+			'get',
119
+			'StringTagFieldTestController/StringTagFieldTestForm/fields/Tags/suggest',
120
+			$parameters
121
+		);
122
+	}
123 123
 }
Please login to merge, or discard this patch.
tests/Stub/StringTagFieldTestController.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -12,21 +12,21 @@
 block discarded – undo
12 12
 
13 13
 class StringTagFieldTestController extends Controller implements TestOnly
14 14
 {
15
-    public function StringTagFieldTestForm()
16
-    {
17
-        $fields = new FieldList(
18
-            $tagField = new StringTagField('Tags')
19
-        );
15
+	public function StringTagFieldTestForm()
16
+	{
17
+		$fields = new FieldList(
18
+			$tagField = new StringTagField('Tags')
19
+		);
20 20
 
21
-        $actions = new FieldList(
22
-            new FormAction('StringTagFieldTestFormSubmit')
23
-        );
21
+		$actions = new FieldList(
22
+			new FormAction('StringTagFieldTestFormSubmit')
23
+		);
24 24
 
25
-        return new Form($this, 'StringTagFieldTestForm', $fields, $actions);
26
-    }
25
+		return new Form($this, 'StringTagFieldTestForm', $fields, $actions);
26
+	}
27 27
 
28
-    public function StringTagFieldTestFormSubmit(DataObject $dataObject, Form $form)
29
-    {
30
-        $form->saveInto($dataObject);
31
-    }
28
+	public function StringTagFieldTestFormSubmit(DataObject $dataObject, Form $form)
29
+	{
30
+		$form->saveInto($dataObject);
31
+	}
32 32
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestBlogPost.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -8,14 +8,14 @@
 block discarded – undo
8 8
 
9 9
 class TagFieldTestBlogPost extends DataObject implements TestOnly
10 10
 {
11
-    private static $table_name = 'TagFieldTestBlogPost';
11
+	private static $table_name = 'TagFieldTestBlogPost';
12 12
 
13
-    private static $db = [
14
-        'Title'   => 'Text',
15
-        'Content' => 'Text'
16
-    ];
13
+	private static $db = [
14
+		'Title'   => 'Text',
15
+		'Content' => 'Text'
16
+	];
17 17
 
18
-    private static $many_many = [
19
-        'Tags' => TagFieldTestBlogTag::class
20
-    ];
18
+	private static $many_many = [
19
+		'Tags' => TagFieldTestBlogTag::class
20
+	];
21 21
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestController.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -13,21 +13,21 @@
 block discarded – undo
13 13
 
14 14
 class TagFieldTestController extends Controller implements TestOnly
15 15
 {
16
-    public function TagFieldTestForm()
17
-    {
18
-        $fields = new FieldList(
19
-            $tagField = new TagField('Tags', '', new DataList('TagFieldTestBlogTag'))
20
-        );
16
+	public function TagFieldTestForm()
17
+	{
18
+		$fields = new FieldList(
19
+			$tagField = new TagField('Tags', '', new DataList('TagFieldTestBlogTag'))
20
+		);
21 21
 
22
-        $actions = new FieldList(
23
-            new FormAction('TagFieldTestFormSubmit')
24
-        );
22
+		$actions = new FieldList(
23
+			new FormAction('TagFieldTestFormSubmit')
24
+		);
25 25
 
26
-        return new Form($this, 'TagFieldTestForm', $fields, $actions);
27
-    }
26
+		return new Form($this, 'TagFieldTestForm', $fields, $actions);
27
+	}
28 28
 
29
-    public function TagFieldTestFormSubmit(DataObject $dataObject, Form $form)
30
-    {
31
-        $form->saveInto($dataObject);
32
-    }
29
+	public function TagFieldTestFormSubmit(DataObject $dataObject, Form $form)
30
+	{
31
+		$form->saveInto($dataObject);
32
+	}
33 33
 }
Please login to merge, or discard this patch.
tests/Stub/TagFieldTestBlogTag.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -8,15 +8,15 @@
 block discarded – undo
8 8
 
9 9
 class TagFieldTestBlogTag extends DataObject implements TestOnly
10 10
 {
11
-    private static $table_name = 'TagFieldTestBlogTag';
11
+	private static $table_name = 'TagFieldTestBlogTag';
12 12
 
13
-    private static $default_sort = '"TagFieldTestBlogTag"."ID" ASC';
13
+	private static $default_sort = '"TagFieldTestBlogTag"."ID" ASC';
14 14
 
15
-    private static $db = [
16
-        'Title' => 'Varchar(200)'
17
-    ];
15
+	private static $db = [
16
+		'Title' => 'Varchar(200)'
17
+	];
18 18
 
19
-    private static $belongs_many_many = [
20
-        'BlogPosts' => TagFieldTestBlogPost::class
21
-    ];
19
+	private static $belongs_many_many = [
20
+		'BlogPosts' => TagFieldTestBlogPost::class
21
+	];
22 22
 }
Please login to merge, or discard this patch.
tests/Stub/StringTagFieldTestBlogPost.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -7,11 +7,11 @@
 block discarded – undo
7 7
 
8 8
 class StringTagFieldTestBlogPost extends DataObject implements TestOnly
9 9
 {
10
-    private static $table_name = 'StringTagFieldTestBlogPost';
10
+	private static $table_name = 'StringTagFieldTestBlogPost';
11 11
 
12
-    private static $db = [
13
-        'Title' => 'Text',
14
-        'Content' => 'Text',
15
-        'Tags' => 'Text',
16
-    ];
12
+	private static $db = [
13
+		'Title' => 'Text',
14
+		'Content' => 'Text',
15
+		'Tags' => 'Text',
16
+	];
17 17
 }
Please login to merge, or discard this patch.
src/TagField.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
         Requirements::javascript('silverstripe/tagfield:client/dist/js/bundle.js');
205 205
 
206 206
         $schema = [
207
-            'name' => $this->getName() . '[]',
207
+            'name' => $this->getName().'[]',
208 208
             'lazyLoad' => $this->getShouldLazyLoad(),
209 209
             'creatable' => $this->getCanCreate(),
210 210
             'multiple' => $this->getIsMultiple(),
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
         $titleField = $this->getTitleField();
412 412
 
413 413
         $query = $source
414
-            ->filter($titleField . ':PartialMatch:nocase', $term)
414
+            ->filter($titleField.':PartialMatch:nocase', $term)
415 415
             ->sort($titleField)
416 416
             ->limit($this->getLazyLoadItemLimit());
417 417
 
Please login to merge, or discard this patch.
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -24,420 +24,420 @@
 block discarded – undo
24 24
  */
25 25
 class TagField extends DropdownField
26 26
 {
27
-    /**
28
-     * @var array
29
-     */
30
-    private static $allowed_actions = array(
31
-        'suggest'
32
-    );
33
-
34
-    /**
35
-     * @var bool
36
-     */
37
-    protected $shouldLazyLoad = false;
38
-
39
-    /**
40
-     * @var int
41
-     */
42
-    protected $lazyLoadItemLimit = 10;
43
-
44
-    /**
45
-     * @var bool
46
-     */
47
-    protected $canCreate = true;
48
-
49
-    /**
50
-     * @var string
51
-     */
52
-    protected $titleField = 'Title';
53
-
54
-    /**
55
-     * @var DataList
56
-     */
57
-    protected $sourceList;
58
-
59
-    /**
60
-     * @var bool
61
-     */
62
-    protected $isMultiple = true;
63
-
64
-    /**
65
-     * @param string $name
66
-     * @param string $title
67
-     * @param null|DataList $source
68
-     * @param null|DataList $value
69
-     * @param string $titleField
70
-     */
71
-    public function __construct($name, $title = '', $source = [], $value = null, $titleField = 'Title')
72
-    {
73
-        $this->setSourceList($source);
74
-        $this->setTitleField($titleField);
75
-        parent::__construct($name, $title, $source, $value);
76
-    }
77
-
78
-    /**
79
-     * @return bool
80
-     */
81
-    public function getShouldLazyLoad()
82
-    {
83
-        return $this->shouldLazyLoad;
84
-    }
85
-
86
-    /**
87
-     * @param bool $shouldLazyLoad
88
-     *
89
-     * @return static
90
-     */
91
-    public function setShouldLazyLoad($shouldLazyLoad)
92
-    {
93
-        $this->shouldLazyLoad = $shouldLazyLoad;
94
-
95
-        return $this;
96
-    }
97
-
98
-    /**
99
-     * @return int
100
-     */
101
-    public function getLazyLoadItemLimit()
102
-    {
103
-        return $this->lazyLoadItemLimit;
104
-    }
105
-
106
-    /**
107
-     * @param int $lazyLoadItemLimit
108
-     *
109
-     * @return static
110
-     */
111
-    public function setLazyLoadItemLimit($lazyLoadItemLimit)
112
-    {
113
-        $this->lazyLoadItemLimit = $lazyLoadItemLimit;
114
-
115
-        return $this;
116
-    }
117
-
118
-    /**
119
-     * @return bool
120
-     */
121
-    public function getIsMultiple()
122
-    {
123
-        return $this->isMultiple;
124
-    }
125
-
126
-    /**
127
-     * @param bool $isMultiple
128
-     *
129
-     * @return static
130
-     */
131
-    public function setIsMultiple($isMultiple)
132
-    {
133
-        $this->isMultiple = $isMultiple;
134
-
135
-        return $this;
136
-    }
137
-
138
-    /**
139
-     * @return bool
140
-     */
141
-    public function getCanCreate()
142
-    {
143
-        return $this->canCreate;
144
-    }
145
-
146
-    /**
147
-     * @param bool $canCreate
148
-     *
149
-     * @return static
150
-     */
151
-    public function setCanCreate($canCreate)
152
-    {
153
-        $this->canCreate = $canCreate;
154
-
155
-        return $this;
156
-    }
157
-
158
-    /**
159
-     * @return string
160
-     */
161
-    public function getTitleField()
162
-    {
163
-        return $this->titleField;
164
-    }
165
-
166
-    /**
167
-     * @param string $titleField
168
-     *
169
-     * @return $this
170
-     */
171
-    public function setTitleField($titleField)
172
-    {
173
-        $this->titleField = $titleField;
174
-
175
-        return $this;
176
-    }
177
-
178
-    /**
179
-     * Get the DataList source. The 4.x upgrade for SelectField::setSource starts to convert this to an array
180
-     * @return DataList
181
-     */
182
-    public function getSourceList()
183
-    {
184
-        return $this->sourceList;
185
-    }
186
-
187
-    /**
188
-     * Set the model class name for tags
189
-     * @param  DataList $className
190
-     * @return self
191
-     */
192
-    public function setSourceList($sourceList)
193
-    {
194
-        $this->sourceList = $sourceList;
195
-        return $this;
196
-    }
197
-
198
-    /**
199
-     * {@inheritdoc}
200
-     */
201
-    public function Field($properties = array())
202
-    {
203
-        Requirements::css('silverstripe/tagfield:client/dist/styles/bundle.css');
204
-        Requirements::javascript('silverstripe/tagfield:client/dist/js/bundle.js');
205
-
206
-        $schema = [
207
-            'name' => $this->getName() . '[]',
208
-            'lazyLoad' => $this->getShouldLazyLoad(),
209
-            'creatable' => $this->getCanCreate(),
210
-            'multiple' => $this->getIsMultiple(),
211
-            'value' => $this->Value(),
212
-            'disabled' => $this->isDisabled() || $this->isReadonly(),
213
-        ];
214
-        if (!$this->getShouldLazyLoad()) {
215
-            $schema['options'] = array_values($this->getOptions()->toNestedArray());
216
-        } else {
217
-            if ($this->Value()) {
218
-                $schema['value'] = $this->getOptions(true)->toNestedArray();
219
-            }
220
-            $schema['optionUrl'] = $this->getSuggestURL();
221
-        }
222
-        $this->setAttribute('data-schema', Convert::array2json($schema));
223
-
224
-        $this->addExtraClass('ss-tag-field');
225
-
226
-        return $this
227
-            ->customise($properties)
228
-            ->renderWith(self::class);
229
-    }
230
-
231
-    /**
232
-     * @return string
233
-     */
234
-    protected function getSuggestURL()
235
-    {
236
-        return Controller::join_links($this->Link(), 'suggest');
237
-    }
238
-
239
-    /**
240
-     * @param bool $onlySelected Only return options that are selected
241
-     * @return ArrayList
242
-     */
243
-    protected function getOptions($onlySelected = false)
244
-    {
245
-        $source = $this->getSourceList();
246
-
247
-        if (!$source) {
248
-            $source = ArrayList::create();
249
-        }
250
-
251
-        $dataClass = $source->dataClass();
252
-        $titleField = $this->getTitleField();
253
-        $values = $this->Value();
254
-
255
-        if ($values) {
256
-            if (is_array($values)) {
257
-                $values = DataList::create($dataClass)->filter($titleField, $values);
258
-            }
259
-        }
260
-        if ($onlySelected) {
261
-            $source = $values;
262
-        }
263
-
264
-        return $source instanceof DataList ? $this->formatOptions($source) : ArrayList::create();
265
-    }
266
-
267
-    /**
268
-     * @param DataList $source
269
-     * @return ArrayList
270
-     */
271
-    protected function formatOptions(DataList $source)
272
-    {
273
-        $options = ArrayList::create();
274
-        $titleField = $this->getTitleField();
275
-
276
-        foreach ($source as $object) {
277
-            $options->push(
278
-                ArrayData::create(array(
279
-                    'Title' => $object->$titleField,
280
-                    'Value' => $object->Title,
281
-                ))
282
-            );
283
-        }
284
-
285
-        return $options;
286
-    }
287
-
288
-    /**
289
-     * {@inheritdoc}
290
-     */
291
-    public function setValue($value, $source = null)
292
-    {
293
-        if ($source instanceof DataObject) {
294
-            $name = $this->getName();
295
-
296
-            if ($source->hasMethod($name)) {
297
-                $value = $source->$name()->column($this->getTitleField());
298
-            }
299
-        } elseif ($value instanceof SS_List) {
300
-            $value = $value->column($this->getTitleField());
301
-        }
302
-
303
-        if (!is_array($value)) {
304
-            return parent::setValue($value);
305
-        }
306
-
307
-        return parent::setValue(array_filter($value));
308
-    }
309
-
310
-    /**
311
-     * {@inheritdoc}
312
-     */
313
-    public function saveInto(DataObjectInterface $record)
314
-    {
315
-        parent::saveInto($record);
316
-
317
-        $name = $this->getName();
318
-        $titleField = $this->getTitleField();
319
-        $source = $this->getSource();
320
-        $values = $this->Value();
321
-        $relation = $record->$name();
322
-        $ids = array();
323
-
324
-        if (!$values) {
325
-            $values = array();
326
-        }
327
-        if (empty($record) || empty($titleField)) {
328
-            return;
329
-        }
330
-
331
-        if (!$record->hasMethod($name)) {
332
-            throw new Exception(
333
-                sprintf("%s does not have a %s method", get_class($record), $name)
334
-            );
335
-        }
336
-
337
-        foreach ($values as $key => $value) {
338
-            // Get or create record
339
-            $record = $this->getOrCreateTag($value);
340
-            if ($record) {
341
-                $ids[] = $record->ID;
342
-                $values[$key] = $record->Title;
343
-            }
344
-        }
345
-
346
-        $relation->setByIDList(array_filter($ids));
347
-    }
348
-
349
-    /**
350
-     * Get or create tag with the given value
351
-     *
352
-     * @param  string $term
353
-     * @return DataObject
354
-     */
355
-    protected function getOrCreateTag($term)
356
-    {
357
-        // Check if existing record can be found
358
-        /** @var DataList $source */
359
-        $source = $this->getSourceList();
360
-        $titleField = $this->getTitleField();
361
-        $record = $source
362
-            ->filter($titleField, $term)
363
-            ->first();
364
-        if ($record) {
365
-            return $record;
366
-        }
367
-
368
-        // Create new instance if not yet saved
369
-        if ($this->getCanCreate()) {
370
-            $dataClass = $source->dataClass();
371
-            $record = Injector::inst()->create($dataClass);
372
-            $record->{$titleField} = $term;
373
-            $record->write();
374
-            return $record;
375
-        } else {
376
-            return false;
377
-        }
378
-    }
379
-
380
-    /**
381
-     * Returns a JSON string of tags, for lazy loading.
382
-     *
383
-     * @param  HTTPRequest $request
384
-     * @return HTTPResponse
385
-     */
386
-    public function suggest(HTTPRequest $request)
387
-    {
388
-        $tags = $this->getTags($request->getVar('term'));
389
-
390
-        $response = new HTTPResponse();
391
-        $response->addHeader('Content-Type', 'application/json');
392
-        $response->setBody(json_encode(array('items' => $tags)));
393
-
394
-        return $response;
395
-    }
396
-
397
-    /**
398
-     * Returns array of arrays representing tags.
399
-     *
400
-     * @param  string $term
401
-     * @return array
402
-     */
403
-    protected function getTags($term)
404
-    {
405
-        /**
406
-         * @var array $source
407
-         */
408
-        $source = $this->getSourceList();
409
-
410
-        $titleField = $this->getTitleField();
411
-
412
-        $query = $source
413
-            ->filter($titleField . ':PartialMatch:nocase', $term)
414
-            ->sort($titleField)
415
-            ->limit($this->getLazyLoadItemLimit());
416
-
417
-        return $this->formatOptions($query)->toNestedArray();
418
-    }
419
-
420
-    /**
421
-     * DropdownField assumes value will be a scalar so we must
422
-     * override validate. This only applies to Silverstripe 3.2+
423
-     *
424
-     * @param Validator $validator
425
-     * @return bool
426
-     */
427
-    public function validate($validator)
428
-    {
429
-        return true;
430
-    }
431
-
432
-    /**
433
-     * Converts the field to a readonly variant.
434
-     *
435
-     * @return TagField_Readonly
436
-     */
437
-    public function performReadonlyTransformation()
438
-    {
439
-        $copy = $this->castedCopy(ReadonlyTagField::class);
440
-        $copy->setSourceList($this->getSourceList());
441
-        return $copy;
442
-    }
27
+	/**
28
+	 * @var array
29
+	 */
30
+	private static $allowed_actions = array(
31
+		'suggest'
32
+	);
33
+
34
+	/**
35
+	 * @var bool
36
+	 */
37
+	protected $shouldLazyLoad = false;
38
+
39
+	/**
40
+	 * @var int
41
+	 */
42
+	protected $lazyLoadItemLimit = 10;
43
+
44
+	/**
45
+	 * @var bool
46
+	 */
47
+	protected $canCreate = true;
48
+
49
+	/**
50
+	 * @var string
51
+	 */
52
+	protected $titleField = 'Title';
53
+
54
+	/**
55
+	 * @var DataList
56
+	 */
57
+	protected $sourceList;
58
+
59
+	/**
60
+	 * @var bool
61
+	 */
62
+	protected $isMultiple = true;
63
+
64
+	/**
65
+	 * @param string $name
66
+	 * @param string $title
67
+	 * @param null|DataList $source
68
+	 * @param null|DataList $value
69
+	 * @param string $titleField
70
+	 */
71
+	public function __construct($name, $title = '', $source = [], $value = null, $titleField = 'Title')
72
+	{
73
+		$this->setSourceList($source);
74
+		$this->setTitleField($titleField);
75
+		parent::__construct($name, $title, $source, $value);
76
+	}
77
+
78
+	/**
79
+	 * @return bool
80
+	 */
81
+	public function getShouldLazyLoad()
82
+	{
83
+		return $this->shouldLazyLoad;
84
+	}
85
+
86
+	/**
87
+	 * @param bool $shouldLazyLoad
88
+	 *
89
+	 * @return static
90
+	 */
91
+	public function setShouldLazyLoad($shouldLazyLoad)
92
+	{
93
+		$this->shouldLazyLoad = $shouldLazyLoad;
94
+
95
+		return $this;
96
+	}
97
+
98
+	/**
99
+	 * @return int
100
+	 */
101
+	public function getLazyLoadItemLimit()
102
+	{
103
+		return $this->lazyLoadItemLimit;
104
+	}
105
+
106
+	/**
107
+	 * @param int $lazyLoadItemLimit
108
+	 *
109
+	 * @return static
110
+	 */
111
+	public function setLazyLoadItemLimit($lazyLoadItemLimit)
112
+	{
113
+		$this->lazyLoadItemLimit = $lazyLoadItemLimit;
114
+
115
+		return $this;
116
+	}
117
+
118
+	/**
119
+	 * @return bool
120
+	 */
121
+	public function getIsMultiple()
122
+	{
123
+		return $this->isMultiple;
124
+	}
125
+
126
+	/**
127
+	 * @param bool $isMultiple
128
+	 *
129
+	 * @return static
130
+	 */
131
+	public function setIsMultiple($isMultiple)
132
+	{
133
+		$this->isMultiple = $isMultiple;
134
+
135
+		return $this;
136
+	}
137
+
138
+	/**
139
+	 * @return bool
140
+	 */
141
+	public function getCanCreate()
142
+	{
143
+		return $this->canCreate;
144
+	}
145
+
146
+	/**
147
+	 * @param bool $canCreate
148
+	 *
149
+	 * @return static
150
+	 */
151
+	public function setCanCreate($canCreate)
152
+	{
153
+		$this->canCreate = $canCreate;
154
+
155
+		return $this;
156
+	}
157
+
158
+	/**
159
+	 * @return string
160
+	 */
161
+	public function getTitleField()
162
+	{
163
+		return $this->titleField;
164
+	}
165
+
166
+	/**
167
+	 * @param string $titleField
168
+	 *
169
+	 * @return $this
170
+	 */
171
+	public function setTitleField($titleField)
172
+	{
173
+		$this->titleField = $titleField;
174
+
175
+		return $this;
176
+	}
177
+
178
+	/**
179
+	 * Get the DataList source. The 4.x upgrade for SelectField::setSource starts to convert this to an array
180
+	 * @return DataList
181
+	 */
182
+	public function getSourceList()
183
+	{
184
+		return $this->sourceList;
185
+	}
186
+
187
+	/**
188
+	 * Set the model class name for tags
189
+	 * @param  DataList $className
190
+	 * @return self
191
+	 */
192
+	public function setSourceList($sourceList)
193
+	{
194
+		$this->sourceList = $sourceList;
195
+		return $this;
196
+	}
197
+
198
+	/**
199
+	 * {@inheritdoc}
200
+	 */
201
+	public function Field($properties = array())
202
+	{
203
+		Requirements::css('silverstripe/tagfield:client/dist/styles/bundle.css');
204
+		Requirements::javascript('silverstripe/tagfield:client/dist/js/bundle.js');
205
+
206
+		$schema = [
207
+			'name' => $this->getName() . '[]',
208
+			'lazyLoad' => $this->getShouldLazyLoad(),
209
+			'creatable' => $this->getCanCreate(),
210
+			'multiple' => $this->getIsMultiple(),
211
+			'value' => $this->Value(),
212
+			'disabled' => $this->isDisabled() || $this->isReadonly(),
213
+		];
214
+		if (!$this->getShouldLazyLoad()) {
215
+			$schema['options'] = array_values($this->getOptions()->toNestedArray());
216
+		} else {
217
+			if ($this->Value()) {
218
+				$schema['value'] = $this->getOptions(true)->toNestedArray();
219
+			}
220
+			$schema['optionUrl'] = $this->getSuggestURL();
221
+		}
222
+		$this->setAttribute('data-schema', Convert::array2json($schema));
223
+
224
+		$this->addExtraClass('ss-tag-field');
225
+
226
+		return $this
227
+			->customise($properties)
228
+			->renderWith(self::class);
229
+	}
230
+
231
+	/**
232
+	 * @return string
233
+	 */
234
+	protected function getSuggestURL()
235
+	{
236
+		return Controller::join_links($this->Link(), 'suggest');
237
+	}
238
+
239
+	/**
240
+	 * @param bool $onlySelected Only return options that are selected
241
+	 * @return ArrayList
242
+	 */
243
+	protected function getOptions($onlySelected = false)
244
+	{
245
+		$source = $this->getSourceList();
246
+
247
+		if (!$source) {
248
+			$source = ArrayList::create();
249
+		}
250
+
251
+		$dataClass = $source->dataClass();
252
+		$titleField = $this->getTitleField();
253
+		$values = $this->Value();
254
+
255
+		if ($values) {
256
+			if (is_array($values)) {
257
+				$values = DataList::create($dataClass)->filter($titleField, $values);
258
+			}
259
+		}
260
+		if ($onlySelected) {
261
+			$source = $values;
262
+		}
263
+
264
+		return $source instanceof DataList ? $this->formatOptions($source) : ArrayList::create();
265
+	}
266
+
267
+	/**
268
+	 * @param DataList $source
269
+	 * @return ArrayList
270
+	 */
271
+	protected function formatOptions(DataList $source)
272
+	{
273
+		$options = ArrayList::create();
274
+		$titleField = $this->getTitleField();
275
+
276
+		foreach ($source as $object) {
277
+			$options->push(
278
+				ArrayData::create(array(
279
+					'Title' => $object->$titleField,
280
+					'Value' => $object->Title,
281
+				))
282
+			);
283
+		}
284
+
285
+		return $options;
286
+	}
287
+
288
+	/**
289
+	 * {@inheritdoc}
290
+	 */
291
+	public function setValue($value, $source = null)
292
+	{
293
+		if ($source instanceof DataObject) {
294
+			$name = $this->getName();
295
+
296
+			if ($source->hasMethod($name)) {
297
+				$value = $source->$name()->column($this->getTitleField());
298
+			}
299
+		} elseif ($value instanceof SS_List) {
300
+			$value = $value->column($this->getTitleField());
301
+		}
302
+
303
+		if (!is_array($value)) {
304
+			return parent::setValue($value);
305
+		}
306
+
307
+		return parent::setValue(array_filter($value));
308
+	}
309
+
310
+	/**
311
+	 * {@inheritdoc}
312
+	 */
313
+	public function saveInto(DataObjectInterface $record)
314
+	{
315
+		parent::saveInto($record);
316
+
317
+		$name = $this->getName();
318
+		$titleField = $this->getTitleField();
319
+		$source = $this->getSource();
320
+		$values = $this->Value();
321
+		$relation = $record->$name();
322
+		$ids = array();
323
+
324
+		if (!$values) {
325
+			$values = array();
326
+		}
327
+		if (empty($record) || empty($titleField)) {
328
+			return;
329
+		}
330
+
331
+		if (!$record->hasMethod($name)) {
332
+			throw new Exception(
333
+				sprintf("%s does not have a %s method", get_class($record), $name)
334
+			);
335
+		}
336
+
337
+		foreach ($values as $key => $value) {
338
+			// Get or create record
339
+			$record = $this->getOrCreateTag($value);
340
+			if ($record) {
341
+				$ids[] = $record->ID;
342
+				$values[$key] = $record->Title;
343
+			}
344
+		}
345
+
346
+		$relation->setByIDList(array_filter($ids));
347
+	}
348
+
349
+	/**
350
+	 * Get or create tag with the given value
351
+	 *
352
+	 * @param  string $term
353
+	 * @return DataObject
354
+	 */
355
+	protected function getOrCreateTag($term)
356
+	{
357
+		// Check if existing record can be found
358
+		/** @var DataList $source */
359
+		$source = $this->getSourceList();
360
+		$titleField = $this->getTitleField();
361
+		$record = $source
362
+			->filter($titleField, $term)
363
+			->first();
364
+		if ($record) {
365
+			return $record;
366
+		}
367
+
368
+		// Create new instance if not yet saved
369
+		if ($this->getCanCreate()) {
370
+			$dataClass = $source->dataClass();
371
+			$record = Injector::inst()->create($dataClass);
372
+			$record->{$titleField} = $term;
373
+			$record->write();
374
+			return $record;
375
+		} else {
376
+			return false;
377
+		}
378
+	}
379
+
380
+	/**
381
+	 * Returns a JSON string of tags, for lazy loading.
382
+	 *
383
+	 * @param  HTTPRequest $request
384
+	 * @return HTTPResponse
385
+	 */
386
+	public function suggest(HTTPRequest $request)
387
+	{
388
+		$tags = $this->getTags($request->getVar('term'));
389
+
390
+		$response = new HTTPResponse();
391
+		$response->addHeader('Content-Type', 'application/json');
392
+		$response->setBody(json_encode(array('items' => $tags)));
393
+
394
+		return $response;
395
+	}
396
+
397
+	/**
398
+	 * Returns array of arrays representing tags.
399
+	 *
400
+	 * @param  string $term
401
+	 * @return array
402
+	 */
403
+	protected function getTags($term)
404
+	{
405
+		/**
406
+		 * @var array $source
407
+		 */
408
+		$source = $this->getSourceList();
409
+
410
+		$titleField = $this->getTitleField();
411
+
412
+		$query = $source
413
+			->filter($titleField . ':PartialMatch:nocase', $term)
414
+			->sort($titleField)
415
+			->limit($this->getLazyLoadItemLimit());
416
+
417
+		return $this->formatOptions($query)->toNestedArray();
418
+	}
419
+
420
+	/**
421
+	 * DropdownField assumes value will be a scalar so we must
422
+	 * override validate. This only applies to Silverstripe 3.2+
423
+	 *
424
+	 * @param Validator $validator
425
+	 * @return bool
426
+	 */
427
+	public function validate($validator)
428
+	{
429
+		return true;
430
+	}
431
+
432
+	/**
433
+	 * Converts the field to a readonly variant.
434
+	 *
435
+	 * @return TagField_Readonly
436
+	 */
437
+	public function performReadonlyTransformation()
438
+	{
439
+		$copy = $this->castedCopy(ReadonlyTagField::class);
440
+		$copy->setSourceList($this->getSourceList());
441
+		return $copy;
442
+	}
443 443
 }
Please login to merge, or discard this patch.