Help sorting chunks by name in snippet

I “wrote”(with AI help) a snippet to create documentation for chunks in a specified category. I would like to sort the chunks by name.

`<?php
// Retrieve chunks by category name (default to ‘Uncategorized’ if no property is provided)
$categoryName = $modx->getOption(‘category’, $scriptProperties, ‘Uncategorized’);

// Get the category object
$category = $modx->getObject(‘modCategory’, array(‘category’ => $categoryName));

$output = ‘’;

if ($category) {
$chunks = $category->getMany(‘Chunks’); // ‘Chunks’ is the name of the aggregate relation

if (!empty($chunks)) {
	
	foreach ($chunks as $chunk) {
		$chunkName = $chunk->get('name');
		$chunkDesc = $chunk->get('description');`

I would like to sort the chunks alphabetically before looping through them. Default sort is by the chunks ID#.

Any advice is welcome.

See The page in action: Reusable Chunks - Design Guide

Thanks
Roy

The function getMany() has a second parameter ($c in the code below) that you can use to sort (or filter) the data:

...
if ($category) { // existing line in your code

    $c = $modx->newQuery('modChunk');
    $c->sortby('name','ASC');

    $chunks = $category->getMany('Chunks', $c); // 'Chunks' is the name of the aggregate relation
    ...

@halftrainedharry

Thank you so much for excellent solution. That worked perfectly!

Roy

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.