Alphabatize items by first name in structure field in front end

Hi there,

I have a structure field with 3 types of info: name, bio, and location. I want to sort the names alphabetically in the front end, either by first name or last name (doesn’t really matter).

This is my blueprint for the contributors page
pages/contributors.yml

fields:
      info:
        label: Info
        type: textarea
        size: medium
      contributors:
        label: Contributors
        type: structure
        sortBy: firstname desc
        fields:
          name:
            label: Name
            type: text
            width: 1/3
          bio:
            label: Bio
            type: text
            width: 1/3
          location:
            label: Location
            type: text
            width: 1/3

This is where I call the structure in my template:
templates/contributors.php

    <?php if ($page->contributors()->isNotEmpty()): ?>    
       
    <div>
                 
         <?php $items = $page->contributors()->toStructure(); foreach ($items as $item): ?>
        
         <div class="contributor-toggle">
            <div class="title"><span><?= $item->name()->html() ?></span></div>
            <div class="content">
                <p><span><?= $item->bio()->html() ?></span>
                <span><?= $item->location()->html() ?></span></p>
                <ul>
                    <?php foreach($articles->filterBy('contributors', $item->name()) as $article): ?>
                        <li><a href="<?php echo $article->url() ?>"><?php echo $article->title() ?></a></li>
                    <?php endforeach ?>
                </ul>
             </div>
        </div>
<?php endforeach ?>
    </div>
<?php endif ?>

I’ve tried a few things, but to no avail. Where would I add the sortBy, in the blueprint, or the template or both?

Thanks!

You can sort a collection with sortBy

$items = $page->contributors()->toStructure()->sortBy('name', 'asc');

On a side note, in the Panel you sort by firstname, but I don’t see that field in your field list.

Yes! that worked thank you as always!