I am fetching a snippet through a route via POST. This snippet uses a variable that comes from a site.php controller, and it is telling me this variable is undefined.
Afaik, I can use render() to return a page including controller code, but a snippet ?
This is the route:
'routes' => [
[
'pattern' => 'categorize',
'method' => 'post',
'action' => function () {
$fetchCategories = get('categories'); // array
$fetchProducts = site()->children()->filterBy('intendedtemplate','product')->filterBy('categories', 'in', $fetchCategories,',');
try {
return json_encode(snippet('product-grid', array('fetchProducts' => $fetchProducts), true));
} catch (Exception $ex) {
return $ex->getMessage();
}
}
],
Thanks
Which variable is undefined?
Hello bvdputte, a variable named lastrow which is calculated on the controller site.php. I thought the specific code was irrelevant, tho.
In the controller:
...
// This helps us remove bottom border in the products that pertain to the last row in home
$lastRow = $products->count() % 3;
// If the modulus returns 0 all rows have 3 elements
if ($lastRow == 0) {
// ...so last row starts at number of products - 3
$lastRow = $products->count() - 3;
} else {
// ...else last row starts at products minus modulus
$lastRow = $products->count() - ($products->count() % 3);
}
...
In the snippet:
...
<li class="product <?= $product->indexOf($products) >= $lastRow ? 'lastRow' : '' ?>" data-product-id="<?= $product->id() ?>">
...
But you don’t pass this over to the snippet, in your array there’s only array('fetchProducts' => $fetchProducts)
.
What you mean is that $lastRow is exposed to the route and I can pass it?
What I mean is that you use the $lastRow
variable in your snippet, but you do not pass it to the snippet nor is it defined inside the snippet itself but only in the controller, so you get the error.
Yes. But how can I access $lastRow, a variable created in site.php controller, in the config file so I can pass it to the snippet, or this cannot be done ?
doesn’t that variable refer to the products? So maybe define
$lastRow = $fetchProducts->count() % 3;
in your route and pass to snippet
Ah yes, that is true, I need to re-define the variable anyway, as it refers to products.
Thanks
And what are you trying to do here, anyway? I wonder if you need this variable at all…
In a grid of 3 columns, I need to know which products pertain to the last row to style them differently.
I define it as such:
$lastRow = $products->count() % 3;
// If the modulus returns 0 all rows have 3 elements
if ($lastRow == 0) {
// ...so last row starts at number of products - 3
$lastRow = $products->count() - 3;
} else {
// ...else last row starts at products minus modulus
$lastRow = $products->count() - ($products->count() % 3);
}
and use it as such:
<li class="product <?= $product->indexOf($products) >= $lastRow ? 'lastRow' : '' ?>">...
…rows do not have to be complete, they can have 1, 2 or 3 products