Glossary API
Since glossary2 4.0.0 we deliver a new Glossary API which you can use to implement a Glossary Index (A-Z list) into your own extension. All the magic you need you'll find in GlossaryService class.
Build a glossary with the API
In class Glossary you will find public method called build
which you have to use. As our API does not know the table to use and does not
know further WHERE conditions, it is up to you to deliver a TYPO3 QueryBuilder
or QueryResult instance as first argument.
Changed in version 7.1.0
The public API of Glossary uses generic types. It accepts
queries and query results of any model, not only of the glossary2 model.
We prefer creating a new method into your Repository and return an Extbase QueryResult object:
/**
* @return QueryResultInterface<int, MyModel>
*/
public function getQueryResultToFindAllEntries(): QueryResultInterface
{
return $this->createQuery()->execute();
}
Alternative you can also return a TYPO3 QueryBuilder instance. BUT: It's up to you now to respect storage PIDs, translation and workspaces:
public function getQueryBuilderToFindAllEntries(): QueryBuilder
{
$table = 'tx_myext_domain_model_whatever';
$query = $this->createQuery();
$queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
$queryBuilder->setRestrictions(
GeneralUtility::makeInstance(FrontendRestrictionContainer::class),
);
// Do not set any SELECT, ORDER BY, GROUP BY statement.
// It will be set by glossary2 API
$queryBuilder
->from($table)
->andWhere(
$queryBuilder->expr()->in(
'pid',
$queryBuilder->createNamedParameter(
$query->getQuerySettings()->getStoragePageIds(),
ArrayParameterType::INTEGER,
),
),
);
return $queryBuilder;
}
Within your controller you can call our API that way:
/**
* @param string $letter Show only records starting with this letter
*/
#[Extbase\Validate(['validator' => 'String', 'param' => 'letter'])]
#[Extbase\Validate([
'validator' => 'StringLength',
'param' => 'letter',
'options' => ['minimum' => 0, 'maximum' => 3],
])]
public function listAction(string $letter = ''): ResponseInterface
{
$companies = $this->companyRepository->findByStartingLetter(
$letter,
$this->settings,
);
$this->view->assign('companies', $companies);
$this->view->assign(
'glossar',
$this->glossaryService->buildGlossary(
$this->myRepository->getQueryResultToFindAllEntries(),
[],
$this->request,
),
);
return $this->htmlResponse();
}
This will transfer the fully rendered HTML Glossar to View.
Please always pass the current Extbase request as third argument. It is
needed by f: to build the A-Z links and to read the TypoScript
settings of glossary2 (plugin.).
Use f: in Fluid Template:
{glossar -> f:format.raw()}
Configure the glossary API
If you want, you can configure our API with second options argument:
$this->view->assign(
'glossar',
$this->glossaryService->buildGlossary(
$this->myRepository->getQueryResultToFindAllEntries(),
[
'settings' => $this->settings,
'templatePath' => 'EXT:myext/Resources/Private/Templates/Glossary.html',
],
$this->request,
),
);
| Name | Type | Default |
|---|---|---|
| string | EXT:glossary2/Resources/Private/Templates/Glossary.html | |
| array | empty | |
| string | glossary2 | |
| string | glossar | |
| string | Glossar | |
| string | list | |
| bool | true | |
| string | title | |
| string | Letter | |
| string | 0-9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z |
-
- Type
- string
- Default
- EXT:glossary2/Resources/Private/Templates/Glossary.html
All rendering of the Glossary is in one file. There is no configuration for partial-, template- nor for layoutRootPaths.
-
- Type
- array
- Default
- empty
If you have your own Template defined, it may be useful to have your own settings inside of your template. Assign your own settings or use settings of your controller (see example above).
-
- Type
- string
- Default
- glossary2
Please change default value to extension name of your extension. This is needed for correct linking of the A-Z list. It will be used within the Plugin namespace in URI:
tx_. Underscores will automatically be converted to UpperCamelCase.extensionname_ pluginname It's your part to check the GET parameters (letter) and adapt your queries to show filtered records.
-
- Type
- string
- Default
- glossar
Please change default value to plugin name of your extension. This is needed for correct linking of the A-Z list. It will be used within the Plugin namespace in URI:
tx_.extensionname_ pluginname It's your part to check the GET parameters (letter) and adapt your queries to show filtered records.
-
- Type
- string
- Default
- Glossar
Please change default value to controller name which should be used for links. It will be used as controller part in URI:
tx_.extensionname_ pluginname [controller Name] It's your part to check the GET parameters (letter) and adapt your queries to show filtered records.
-
- Type
- string
- Default
- list
Please change default value to action name of given controller name above, which should be used for links. It will be used as action part in URI:
tx_.extensionname_ pluginname [action Name] It's your part to check the GET parameters (letter) and adapt your queries to show filtered records.
-
- Type
- bool
- Default
- true
By default the numbers will be represented in A-Z list as 0-9 instead of 0 1 2 3 4 5 6 7 8 9.
-
- Type
- string
- Default
- title
The column of your QueryBuilder to extract the first letters from.
-
- Type
- string
- Default
- Letter
To prevent duplicate usage of column in GROUP BY and ORDER BY we are working with an column alias. If you already have a column called
Letterin your table you should change that property to something unique.
-
- Type
- string
- Default
- 0-9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
If empty it uses the default from ExtensionSettings
These are the allowed letters to be shown in frontend. So, if you remove for example the letter
r, it will not be shown in frontend, regardless if a record starting withris in ResultSet or not.If you disable
mergeyou have to add each individual number here instead of using 0-9.Numbers It is not allowed to use a combination of numbers and a range like: 0, 1-3, 4. It is not allowed to use ranges other that 0-9 like: 0-3, 4-9.
Extend your controller
It is up to you to process the letter in your controller. In most cases you may extend your listAction:
public function listAction(string $letter = ''): ResponseInterface
{
if ($letter) {
$myRecords = $this->myRepo->findByLetter($letter);
} else {
$myRecords = $this->myRepo->findAll();
}
$this->view->assign('myRecords', $myRecords);
return $this->htmlResponse();
}
Extend your repository
Above we have used a new method find. With glossary2 4.1.0 you can
use our API with Extbase Query or Doctrine.
Example for an Extbase query
public function findByLetter(string $letter): QueryResultInterface
{
$glossaryService = GeneralUtility::makeInstance(GlossaryService::class);
$query = $this->createQuery();
$constraints = [];
$constraints[] = $glossaryService->getLetterConstraintForExtbaseQuery(
$query,
'myColumnName',
$letter,
);
return $query->matching($query->logicalAnd(...$constraints))->execute();
}
Example for a Doctrine query
public function findByLetter(string $letter): QueryResultInterface
{
$glossaryService = GeneralUtility::makeInstance(GlossaryService::class);
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('my_table');
$queryBuilder
->select('*')
->from('my_table')
->andWhere(
$glossaryService->getLetterConstraintForDoctrineQuery(
$queryBuilder,
'my_colum_name',
$letter,
),
);
$query = $this->createQuery();
return $query->statement($queryBuilder)->execute();
}
Extend the glossary function
We have added two PSR-14 events to extend functionality of glossary API.
Register your event listeners with the PHP attribute #.
See PSR-14 events for all events of glossary2.
PostProcessFirstLettersEvent
After retrieving the possible first letters from database, we clean, sort and
remove duplicates. The result will then be sent to the event
JWeiland. Use
get to get the letters as simple array:
$firstLetters = [
0 => '0',
1 => 'a',
2 => 'b',
3 => 'c',
...
];
Add or remove letters as you like and set the modified array with
set:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use JWeiland\Glossary2\Event\PostProcessFirstLettersEvent;
use TYPO3\CMS\Core\Attribute\AsEventListener;
#[AsEventListener('my-extension/remove-letter-q')]
final readonly class RemoveLetterEventListener
{
public function __invoke(PostProcessFirstLettersEvent $event): void
{
$event->setFirstLetters(
array_values(array_diff($event->getFirstLetters(), ['q'])),
);
}
}
New in version 7.1.0
The method set was added. Before, the modified letters
could not be passed back to glossary2.
SanitizeValueForCharsetHelperEvent
After retrieving the possible first letters from database, we start a
cleaning process of each individual letter. The letter is converted to
lower case and special chars are mapped to their ASCII representation with
the Charset of TYPO3, for example german umlauts ÄÖÜ to AOU. Only
the first character of the result is used.
If you need further mappings like for french or spain you can use the event
JWeiland. Get the
pre-sanitized value with get and set your mapped value with
set:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use JWeiland\Glossary2\Event\SanitizeValueForCharsetHelperEvent;
use TYPO3\CMS\Core\Attribute\AsEventListener;
#[AsEventListener('my-extension/map-letters')]
final readonly class MapLetterEventListener
{
private const LETTER_MAPPING = [
'ł' => 'l',
'đ' => 'd',
];
public function __invoke(SanitizeValueForCharsetHelperEvent $event): void
{
$event->setValue(strtr($event->getValue(), self::LETTER_MAPPING));
}
}