您需要修改 ProductController(/controllers/front/ProductController.php)
基本上我所做的是检查默认属性是否有库存。如果有库存,则无需再寻找其他地方。
如果没有库存,则获取所有产品属性并循环遍历属性。一旦找到带有库存的属性,删除旧的默认属性并将找到的属性设置为默认属性。
在 productController 类中添加此方法
/*
start set default based on stock
*/
public function getProductAttributes()
{
$sql = "SELECT * FROM " . _DB_PREFIX_ . "product_attribute WHERE
id_product = ". (int) $this->product->id;
return Db::getInstance()->executeS($sql);
}
public function getProductStock($id_product_attribute)
{
return StockAvailable::getQuantityAvailableByProduct($this->product->id,
$id_product_attribute, $this->context->shop->id);
}
public function checkDefault()
{
$id_product_attribute = Product::getDefaultAttribute($this->product->id);
$stk = (int) $this->getProductStock($id_product_attribute);
if( $stk > 0){
return true;
}
return false;
}
public function checkAttributeStock( $id_product_attribute)
{
$stk = $this->getProductStock($id_product_attribute);
if( $stk > 0){
return true;
}
return false;
}
public function setDefaultBasedOnStock()
{
if($this->checkDefault()){
return true;
}
$product_atts = $this->getProductAttributes();
if(count($product_atts) >0){
foreach($product_atts as $attri){
if($this->checkAttributeStock($attri['id_product_attribute'])){
$this->product->deleteDefaultAttributes();
$this->product->setDefaultAttribute($attri['id_product_attribute']);
break;
}
}
}
}
/*
end set default based on stock
*/
然后你需要在 parent::init(); 之后调用 init 方法中的 setDefaultBasedOnStock 方法;
public function init()
{
parent::init();
$this->setDefaultBasedOnStock();
// here is the rest of init code ......
//Do not delete the rest of init code
}
请不要删除其余的 init() 方法代码,只需在 parent::init(); 下方添加这一行 $this->setDefaultBasedOnStock();
最好的方法是覆盖 productController
您可以在 /override/controllers/front/ 文件夹中创建 productController 覆盖类,而不是修改 productController 类
class ProductController extends ProductControllerCore {
// add all the methods above
// including the init method
}
// 添加覆盖后,如果启用了 prestashop 缓存,您可能需要清除缓存。