Call to a member function getAttributes() on null
-
13-12-2020 - |
题
I have a php code for creating a product feed XML, including all the additional attributes of the products. It worked fine until I upgraded from 1.9.3.1
to 1.9.3.4
.
After the upgrade my script gives this error:
PHP Fatal error: Call to a member function getAttributes() on null in /www/new/app/code/core/Mage/Catalog/Block/Product/View/Attributes.php on line 58.
My codepart which takes care of extracting the additional attributes:
$_helper = Mage::helper('catalog/output');
$add = new Mage_Catalog_Block_Product_View_Attributes();
$add->setProduct($productId);
$_additional = $add->getAdditionalData();
$_product = Mage::getModel('catalog/product');
$_product->setStoreId($storeId);
$_product->load($productId);
foreach ($_additional as $_data):
$_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) !='') && (!is_null($_data['label'])) && (!is_null($_data['value'])))
{
$produs->appendChild($xml->createElement(str_replace(" ","_", preg_replace("/[^A-Za-z0-9_ ]/", "",$_data['label'])), str_replace($replace_from, $replace_to, strip_tags($_helper->productAttribute($_product, $_data['value'], $_data['code'])))));
}
endforeach;
What has changed between the two versions and what should I modify in my code to make it work again?
解决方案
Looking into the source of app/code/core/Mage/Catalog/Block/Product/View/Attributes.php it appears that $product = $this->getProduct();
(from line 57) is not returning the product, backtracking to the getProduct() method, tells me that the product has not been set in the registry ie: Mage::registry('product'); returns NULL. You could try the following code to see if it fixes the issue.
$_helper = Mage::helper('catalog/output');
$add = new Mage_Catalog_Block_Product_View_Attributes();
$add->setProduct($productId);
$_product = Mage::getModel('catalog/product');
$_product->setStoreId($storeId);
$_product->load($productId);
Mage::register('product', $_product);
$_additional = $add->getAdditionalData();
foreach ($_additional as $_data):
$_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) !='') && (!is_null($_data['label'])) && (!is_null($_data['value'])))
{
$produs->appendChild($xml->createElement(str_replace(" ","_", preg_replace("/[^A-Za-z0-9_ ]/", "",$_data['label'])), str_replace($replace_from, $replace_to, strip_tags($_helper->productAttribute($_product, $_data['value'], $_data['code'])))));
}
endforeach;
Mage::unregister('product');