Find latest record otherwise all others if statement

6 posts by 3 authors in: Forums > CMS Builder
Last Post: September 9, 2019   (RSS)

By Zicky - September 9, 2019

Howdy folks,

I'm trying to find the latest record in a foreach loop and show additional information for the newest record, and all other older records I only wish to show their titles. But I'm struggling to figure this out. Any suggestions on how to accomplish this are much appreciated. 

  // load records from 'digital_magazine'
  list($digital_magazineRecords, $digital_magazineMetaData) = getRecords(array(
    'tableName'   => 'digital_magazine',
    'loadUploads' => true,
    'allowSearch' => false,
  ));

<?php foreach ($digital_magazineRecords as $record): ?>

// find only the latest record and show the title and cover image.

   <h1><?php echo htmlencode($record['title']) ?></h1>
   <?php foreach ($record['cover_image'] as $index => $upload): ?>
      <img src="<?php echo htmlencode($upload['thumbUrlPath2']) ?>"/>
   <?php endforeach ?>

// all other records show only the record title.

<h4><?php echo htmlencode($record['title']) ?></h4>

<?php endforeach ?>

Thanks, Zick

By daniel - September 9, 2019

Hi Zicky,

To do something like this, you can modify the foreach to provide the "key" of the current element which, in the case of these records, should be a numerical index starting with 0. This can then be used to check for the first item. It could look something like this:

<?php foreach ($digital_magazineRecords as $key => $record): ?>
<?php if ($key == 0): ?>

   <h1><?php echo htmlencode($record['title']) ?></h1>
   <?php foreach ($record['cover_image'] as $index => $upload): ?>
      <img src="<?php echo htmlencode($upload['thumbUrlPath2']) ?>"/>
   <?php endforeach ?>

<?php else: ?>

   <h4><?php echo htmlencode($record['title']) ?></h4>

<?php endif; ?>
<?php endforeach ?>

Note that this checks for the first item in the records array, which isn't necessarily the newest record, depending on what parameters are being used in getRecords().

Let me know if that suits your needs, or if you have any questions!

Thanks,

Daniel
Technical Lead
interactivetools.com

By gkornbluth - September 9, 2019

I knew my approach wasn't particularly elegant...

Thanks Daniel

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!

Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By Zicky - September 9, 2019

Thanks Jerry!

'orderBy' => "createdDate DESC",

That was part of the solution I needed. 

By Zicky - September 9, 2019

Thanks Daniel and Jerry,

I applied both of your suggestions and everything is working great now!

Thank you both!!!

Zick