EEConf 2024 is around the corner! EEConf 2024
This may be a dumb question, but how do I get a plugin to loop the way a module does.
For example, when you do a {exp:gallery:entries}, EE loops over the enclosing content for each image.
I would like my plugin to loop as well so that I list the sub-categories for a given category.
Here is my code, which only prints out the last category:
function Categoree()
{
global $DB, $IN, $TMPL, $FNS;
if ( ! preg_match("#(^|\/)C(\d+)#", $IN->QSTR, $match))
{
return '';
}
$query = $DB->query("SELECT exp_gallery_categories.cat_id, exp_gallery_categories.cat_name
FROM exp_gallery_categories, exp_galleries
WHERE exp_gallery_categories.gallery_id = exp_galleries.gallery_id AND
exp_gallery_categories.parent_id = '".$DB->escape_str($match['2'])."'");
if ($query->num_rows == 0)
{
return '';
}
foreach ( $query->result as $row )
{
$tagdata = $FNS->prep_conditionals($TMPL->tagdata, $row);
foreach ($TMPL->var_single as $key => $val)
{
switch ($val)
{
case "cat_name":
$tagdata = $TMPL->swap_var_single($val, $row['cat_name'], $tagdata);
break;
case "cat_id":
$tagdata = $TMPL->swap_var_single($val, $row['cat_id'], $tagdata);
break;
}
}
}
$this->return_data = $tagdata;
}
The query works fine and returns the correct values, but I am only seeing the last one on my page. My template code is:
{exp:categoree}
{cat_name} - {cat_id}
{/exp:categoree}
Are you clear on what $TMPL->tagdata is?
$tagdata = $FNS->prep_conditionals($TMPL->tagdata, $row);
You’re resetting $tagdata within each iteration of the loop. You aren’t building a string that continues to add output in each loop. Removed from EE entirely, it’s the difference between:
$foo = 'whatever ';
for ($i = 0;$i < 10; $++)
{
$bar = $foo;
}
echo $bar;
vs.
$foo = 'whatever ';
for ($i = 0;$i < 10; $++)
{
$bar .= $foo;
}
echo $bar;
OK, for those of you following my oh-so-painful learning process, this seems to work:
$tagdata = '';
foreach ( $query->result as $row )
{
$tagdata .= $FNS->prep_conditionals($TMPL->tagdata, $row);
foreach ($TMPL->var_single as $key => $val)
{
switch ($val)
{
case "cat_name":
$tagdata = $TMPL->swap_var_single($val, $row['cat_name'], $tagdata);
break;
case "cat_id":
$tagdata = $TMPL->swap_var_single($val, $row['cat_id'], $tagdata);
break;
}
}
}
$this->return_data = $tagdata;
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.