Skip to content

Instantly share code, notes, and snippets.

@jenswittmann
Last active February 15, 2021 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenswittmann/f316b9e3e588b0ba49cc03203264d058 to your computer and use it in GitHub Desktop.
Save jenswittmann/f316b9e3e588b0ba49cc03203264d058 to your computer and use it in GitHub Desktop.
Get alphabetical Letters from MODX PDO Collection
<?php
/**
* alphabeticalLetters
*
* DESCRIPTION
*
* This Snippet return alphabetical Letters from Collection
*
* PROPERTIES:
*
* &class required
* &tpl required
*
* USAGE:
*
* [[alphabeticalLetters?
* &class=`glossary`
* &index=`title`
* &tpl=`@INLINE <li>[[+title]]</li>` ]]
*
*/
# vars
$inlineTplPrefix = "@INLINE";
$tpl = $modx->getOption("tpl", $scriptProperties, $inlineTplPrefix . " ");
$class = $modx->getOption("class", $scriptProperties, false);
$index = $modx->getOption("index", $scriptProperties, "title");
$pdo = $modx->getService("pdoFetch");
$placeholders = [];
# get items
$items = $pdo->getCollection(
$class,
[],
[
"select" => "id, " . $index,
"sortby" => '{"' . $index . '":"ASC"}',
"limit" => 0,
]
);
# get letters
foreach ($items as $item) {
$letter = strtoupper(substr($item[$index], 0, 1));
if (!$placeholders[$letter]) {
$placeholders[$letter] = [
"id" => $item["id"],
"letter" => $letter,
];
}
}
# return
$output = [];
if (substr($tpl, 0, strlen($inlineTplPrefix)) == $inlineTplPrefix) {
$chunk = $modx->newObject("modChunk", [
"name" => "{tmp}-{" . uniqid() . "}",
]);
$chunk->setCacheable(false);
$tpl = str_replace($inlineTplPrefix, "", $tpl);
foreach ($placeholders as $placeholder) {
$output[] = $chunk->process($placeholder, $tpl);
}
} else {
foreach ($placeholders as $placeholder) {
$output[] = $modx->getChunk($tpl, $placeholder);
}
}
return implode("", $output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment