Skip to content

Instantly share code, notes, and snippets.

@matdave
Forked from anonymous/scCartQuantities
Last active June 19, 2017 12:20
Show Gist options
  • Save matdave/d7fcc63580cbad2da3d511440db9fa14 to your computer and use it in GitHub Desktop.
Save matdave/d7fcc63580cbad2da3d511440db9fa14 to your computer and use it in GitHub Desktop.
modmore SimpleCart - Adjust cart quantities based on stock
<?php
/**
* Created by PhpStorm.
* User: Mat
* Date: 6/19/2017
* Time: 3:33 AM
*/
$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) {
$productid = $product->id;
$resource = $modx->getObject('modResource',$productid);
$meta = (($resource instanceof scProductResource) ? $resource->getProductMeta() : $sc->getDeprecatedProductMeta($resource));
if(
$product->totals['quantity'] > $meta['product_stock'] && $meta['product_stock'] !== null
){
foreach($controller->storageData['products'] as $key=>$value){
if($value['productid'] == $productid){
$controller->storageData['products'][$key]['quantity'] = $meta['product_stock'];
if($meta['product_stock'] <= 0){
unset($controller->storageData['products'][$key]);
}
$controller->setStorageData();
$url = $modx->makeUrl($modx->resource->get('id'), '', array('quantity'=>'adjusted'), 'https');
$modx->sendRedirect($url);
}
}
}
}
if(isset($_GET['quantity']) && $_GET['quantity'] == 'adjusted'){
echo '<div class="btn success">Product quantities have been adjusted based on current availability.</div>';
}
@Mark-H
Copy link

Mark-H commented Jun 19, 2017

It's better to use return in snippets, instead of echo due to the way the parser handles things ;) Other than that, looks very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment