I got following error when tried to save product from collection:
Invalid method Varien_Object::save(Array())
And here is full code (I know, that it is ugly, but now I try refactor it):
public function postAction()
{
$sku = Mage::app()->getRequest()->getParam('sku');
$file = Mage::app()->getRequest()->getParam('file');
if (empty($sku) or empty($file)) {
echo "FALSE";
return;
}
$path = Mage::getBaseDir() . "/media/photosimport/";
$filepath = $path . $file;
$img_save_mode = array('image', 'small_image', 'thumbnail');
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
if (!$product->getId()) {
echo "FALSE";
return;
}
Mage::log($sku . ' =>' . $product->getName(), null, 'photosimport.log');
$filename = pathinfo($file, PATHINFO_FILENAME);
$filenameArray = explode("_",$filename); //0 - SKU, 1 - image name
$imagename = (isset($filenameArray[1]) && !empty($filenameArray[1])) ? $filenameArray[1] : null;
$prod = Mage::getModel('catalog/product')->load($product->getId());
$galleryData = $prod->getData('media_gallery');
foreach ($galleryData['images'] as $galleryImage)
{
$gf = explode("/", $galleryImage['file']);
if ($gf[count($gf) - 1] == $file) {
echo "UPDATE";
unlink(Mage::getBaseDir() . '/media/catalog/product' . $galleryImage['file']);
rename($filepath, Mage::getBaseDir() . '/media/catalog/product' . $galleryImage['file']);
@unlink($filepath);
}
}
if (file_exists($filepath)) {
try {
if (empty($imagename)) {
$product->addImageToMediaGallery($filepath, $img_save_mode, true, false);
} else {
$product->addImageToMediaGallery($filepath, false, true, false);
}
Mage::log($sku . ' ok', null, 'photosimport.log');
} catch (Exception $e) {
Mage::log('error: ' . $e->getMessage(), null, 'photosimport.log');
echo "FALSE";
echo $e->getMessage();
return;
}
} else {
Mage::log(
'Product does not have an image or the path is incorrect. Path was: '.$filepath,
null,
'photosimport.log'
);
echo "FALSE";
return;
}
try {
$product->save();
} catch (Exception $e) {
echo $e->getMessage();
}
@unlink($filepath);
echo "OK";
}
Please, help me to fix that! I tried to use saveAttribute via resource model, but it didn't work too.
Best Answer
Main issue at
product exits or not.When you have use Mage::getModel('catalog/product')->loadByAttribute('sku', $sku) then as per as
OOP concept ,$product
wasgave an object
that means' !$product goes to false ` .In this case,you need
to use getId()
.when a product is not exits then it getId() getter function give the value blank