nclark
(Nick Clark)
July 4, 2016, 6:02pm
#1
I’m interested in being able to detect if a particular item is in the cart to drive a couple conditionals. Is there any hidden methods I could link into to allow me to loop over the cart contents and display chunks based on said content?
Would like to end up with something like:
[[!cartIncludes? &productId=25
&then=chunk1
&else=chunk2
]]
I’m guessing i’ll have to load both chunks into memory and do the conditional via javascript but wasn’t sure if there was a way to access the data if I used the site cache for the cart instead of cookies.
mhamstra
(Mark Hamstra)
July 6, 2016, 1:32pm
#2
Yeah, you can interact with the cart programmatically.
Something along these lines will first load the CartContentsController:
$sc = $modx->getService('simplecart','SimpleCart',$modx->getOption('simplecart.core_path',null,$modx->getOption('core_path').'components/simplecart/').'model/simplecart/',$scriptProperties);
if (!($sc instanceof SimpleCart)) return '';
$controller = $sc->loadController('Cart', 'ContentsController');
Then load the products into the controller:
$controller->initialize();
$controller->loadProducts();
and then you have a limited copy of the products in $controller->data['products']
. So you can do something like this:
foreach ($controller->data['products'] as $product) {
if ($product->id == 15) {
return '[[$chunk1]]';
}
}
return '[[$chunk2]]';
(All of the above is untested)
2 Likes
nclark
(Nick Clark)
July 6, 2016, 4:50pm
#3
Thanks Mark, that is awesome that it can be accessed like that!
The only change I had to make was to use:
$controller->getProducts()
in the foreach instead of
$controller->data['products']
so a bare bones snippet would look like this:
$sc = $modx->getService('simplecart','SimpleCart',$modx->getOption('simplecart.core_path',null,$modx- >getOption('core_path').'components/simplecart/').'model/simplecart/',$scriptProperties);
if (!($sc instanceof SimpleCart)) return '';
$controller = $sc->loadController('Cart', 'ContentsController');
$controller->initialize();
$controller->loadProducts();
foreach ($controller->getProducts() as $product) {
if ($product->parent == 34) {
return 'true';
}
}
return 'false';
mhamstra
(Mark Hamstra)
July 6, 2016, 5:09pm
#4
Ahh, I missed the getProducts but should’ve known Nice work.
1 Like