Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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