Re: [Perchpole] Show Image from Parent Category
Hi Perch,
Each category has a field with the "num" of its parent category (called "parentNum".) Using this, it's possible to look up any fields associated with the parent.
To make these lookups possible, the simplest solution is to create an array for lookups:
list($categoriesRecords, $selectedCategory) = getCategories(array(
'tableName' => 'categories',
));
$categoriesRecordsByNum = array_combine(array_pluck($categoriesRecords, "num"), $categoriesRecords);
Now that we can do lookups, let's look up the parent of each category as we're going through them:
<?php foreach ($categoriesRecords as $categoryRecord): ?>
<?php $parent = @$categoriesRecordsByNum[$categoryRecord['parentNum']] ?>
...
Note that some categories (namely top-level ones) won't have a parent, so $parent will be null.
Before we fiddle with uploads, let's make sure everything works with a simpler field, like "name". Let's output the parent category's name in parenthesis beside the current category's name:
<a href="<?php echo $categoryRecord['_link'] ?>"><?php echo $categoryRecord['name'] ?></a> (<?php echo @$parent['name'] ?>)
Make sure that works before moving on, then get rid of it.
For simplicity, I'm going to assume that you want to display a custom <img> if the parent category has one uploaded, otherwise a default <img src="bullet.gif">. If you need to style the <li>s, that'd be a bit more complicated. Let me know if that's the case.
First we check to make sure there is a parent and the parent's upload field (I'm assuming it's called "icon" here) has at least 1 image in it; if so, we snag the first upload record and display it, otherwise we output the default image:
<?php if ($parent && sizeof($parent['icon']) > 0): ?>
<?php $icon = $parent['icon'][0] ?>
<img src="<?php echo $icon['urlPath'] ?>">
<?php else: ?>
<img src="bullet.gif">
<?php endif ?>
<a href="<?php echo $categoryRecord['_link'] ?>"><?php echo $categoryRecord['name'] ?></a>
I hope this all makes sense! Please let me know if you have any questions.
All the best,
Chris