Umair Umair - 2 months ago 18
PHP Question

Error saving product after removing product images - Magento ver. 1.8.1.0

I have been trying to add/edit images to magento product.

I have this code

require_once("../test/app/Mage.php");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleProduct = Mage::getModel('catalog/product');
$simpleProduct->load($_POST['id_in_magento']);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApiItems = $mediaApi->items($simpleProduct->getId());

foreach ($mediaApiItems as $item) {
$datatemp = $mediaApi->remove($simpleProduct->getId(), $item['file']);
}
$simpleProduct->getResource()->save($simpleProduct);

foreach (unserialize($_POST['product_groups_images']) as $img) {
$simpleProduct->addImageToMediaGallery($img, array('image', 'small_image', 'thumbnail'), false, false);
}
// ERROR on this line...
$simpleProduct->getResource()->save($simpleProduct);


This code works and does not work too. Here is how.

1) If product has no images then code works.

2) If product has images previously, it deletes images successfully (I have confirmed from product frontend link that images are deleted), but then (tries to) add images and when trying to save it that error occurs.

This is complete error

`SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`coszi_test`.`catalog_product_entity_media_gallery_value`, CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID` FOREIGN KEY (`value_id`) REFERENCES `catalog_product_enti)`

Answer

Change code like this

 foreach ($mediaApiItems as $item) {
    $datatemp = $mediaApi->remove($simpleProduct->getId(), $item['file']);
}
$simpleProduct->getResource()->save($simpleProduct);

to

    foreach ($mediaApiItems as $item) {
    $datatemp = $mediaApi->remove($simpleProduct->getId(), $item['file']);
}

Remove this save

$simpleProduct->getResource()->save($simpleProduct);

Hope it will works..