Skip to content

Instantly share code, notes, and snippets.

@georgringer
Last active November 3, 2021 09:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save georgringer/54046718ee03c6161cca85d419570a1c to your computer and use it in GitHub Desktop.
Save georgringer/54046718ee03c6161cca85d419570a1c to your computer and use it in GitHub Desktop.
Get categories of a table

Usage with

<xxx:category as="categories" id="{data.uid}" table="tt_content" field="categories" falField="images">
    <f:debug inline="1">{categories}</f:debug>
</xxx:category>
<?php
declare(strict_types=1);
namespace GeorgRinger\SitePackage\ViewHelpers;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
class CategoryViewHelper extends AbstractViewHelper
{
/**
* @var bool
*/
protected $escapeOutput = false;
/**
* Initialize arguments.
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('as', 'string', 'as', true);
$this->registerArgument('table', 'string', 'Table name of record', true);
$this->registerArgument('field', 'string', 'Category field', true);
$this->registerArgument('id', 'int', 'ID of record', true);
$this->registerArgument('falField', 'string', 'Comma separated list of fal fields', false, '');
}
public function render(): string
{
$as = $this->arguments['as'];
$categories = $this->getCategories($this->arguments);
$this->templateVariableContainer->add($as, $categories);
$output = $this->renderChildren();
$this->templateVariableContainer->remove($as);
return $output;
}
protected function getCategories(array $arguments): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');
$rows = $queryBuilder
->select('s.*')
->from('sys_category', 's')
->rightJoin('s', 'sys_category_record_mm', 'mm', 's.uid=mm.uid_local')
->where(
$queryBuilder->expr()->eq('mm.uid_foreign', $queryBuilder->createNamedParameter($arguments['id'], \PDO::PARAM_INT)),
$queryBuilder->expr()->eq('mm.tablenames', $queryBuilder->createNamedParameter($arguments['table'], \PDO::PARAM_STR)),
$queryBuilder->expr()->eq('mm.fieldname', $queryBuilder->createNamedParameter($arguments['field'], \PDO::PARAM_STR))
)
->execute()
->fetchAll();
if ($arguments['falField']) {
$falFields = GeneralUtility::trimExplode(',', $arguments['falField'], true);
foreach ($rows as &$row) {
foreach ($falFields as $falField) {
if (!isset($row[$falField]) || (int)$row[$falField] === 0) {
continue;
}
try {
$fileObjects = GeneralUtility::makeInstance(FileRepository::class)
->findByRelation('sys_category', $falField, $row['uid']);
$row[$falField] = $fileObjects;
} catch (\Exception $e) {
// do nothing
}
}
}
}
return $rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment