|
15 | 15 | use SilverStripe\Forms\HiddenField; |
16 | 16 | use stdClass; |
17 | 17 | use SilverStripe\Forms\Form; |
| 18 | +use SilverStripe\Security\Member; |
18 | 19 |
|
19 | 20 | class SearchableDropdownTraitTest extends SapphireTest |
20 | 21 | { |
@@ -261,4 +262,55 @@ public function testLazyLoadedDoesntCallGetSource(string $fieldClass, string $me |
261 | 262 | $mockField->setForm(new Form()); |
262 | 263 | $mockField->$methodToCall(); |
263 | 264 | } |
| 265 | + |
| 266 | + public static function provideSearchDataObjectWithMethodForLabelField(): array |
| 267 | + { |
| 268 | + return [ |
| 269 | + 'single' => [ |
| 270 | + 'term' => 'alex', |
| 271 | + 'expected' => '[{"value":0,"label":"Aziel, Alex"}]', |
| 272 | + ], |
| 273 | + 'multi' => [ |
| 274 | + 'term' => 'z', |
| 275 | + 'expected' => '[{"value":0,"label":"Aziel, Alex"},{"value":0,"label":"Cazton, Cindy"}]', |
| 276 | + ], |
| 277 | + 'email' => [ |
| 278 | + 'term' => '@example.com', |
| 279 | + 'expected' => implode('', [ |
| 280 | + '[{"value":0,"label":"Aziel, Alex"},{"value":0,"label":"Brown, Bob"}', |
| 281 | + ',{"value":0,"label":"Cazton, Cindy"}]', |
| 282 | + ]), |
| 283 | + ], |
| 284 | + ]; |
| 285 | + } |
| 286 | + |
| 287 | + /** |
| 288 | + * Member has a method getTitle() that returns "Surname, FirstName" |
| 289 | + * The default label field on the field is "Title", which doesn't exist on the Member database table |
| 290 | + * It should fall back to using search context in this scenario |
| 291 | + * |
| 292 | + * @dataProvider provideSearchDataObjectWithMethodForLabelField |
| 293 | + */ |
| 294 | + public function testSearchDataObjectWithMethodForLabelField(string $term, string $expected): void |
| 295 | + { |
| 296 | + $data = [ |
| 297 | + ['FirstName' => 'Alex', 'Surname' => 'Aziel', 'Email' => 'aaron.aziel@example.com'], |
| 298 | + ['FirstName' => 'Bob', 'Surname' => 'Brown', 'Email' => 'bob.brown@example.com'], |
| 299 | + ['FirstName' => 'Cindy', 'Surname' => 'Cazton', 'Email' => 'cindy.cazton@example.com'], |
| 300 | + ]; |
| 301 | + foreach ($data as $row) { |
| 302 | + $member = new Member($row); |
| 303 | + $member->write(); |
| 304 | + } |
| 305 | + // 4 members because of the 3 members above and the default admin member |
| 306 | + $this->assertSame(4, Member::get()->count()); |
| 307 | + $field = new SearchableDropdownField('MyField', 'MyField', Member::get()); |
| 308 | + $field->setLabelField('Title'); |
| 309 | + $request = new HTTPRequest('GET', 'someurl', ['term' => $term]); |
| 310 | + $request->addHeader('X-SecurityID', SecurityToken::getSecurityID()); |
| 311 | + $body = $field->search($request)->getBody(); |
| 312 | + // Replace the member ID value with 0 to make the test more stable |
| 313 | + $body = preg_replace('/"value":[0-9]+/', '"value":0', $body); |
| 314 | + $this->assertSame($expected, $body); |
| 315 | + } |
264 | 316 | } |
0 commit comments