Magento – Programmatically Trigger Admin Save Action on Product

admince-1.8.1.0controllersproduct

I have been troubleshooting a problem for hours. I can't explain why, but the problem is resolved when I go to the product in admin and click "Save" for that product (without changing anything). I am guessing this has something to do with the batch upload.

I have written a script that loops through all products and then calls save(), but this doesn't have the same effect as saving the product via the admin controller action (see Mage_Adminhtml_Catalog_ProductController). Here is my basic script, I change the short description just for testing the save success:

#!/usr/local/bin/php

<?php
require 'app/Mage.php';
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
foreach ($products as $product) {
    $product->load();
    echo 'Product: ' . $product->getId() . ' - ' . $product->getName() . "\xA";

    $product->setShortDescription('N/A');
    $product->save();
}
?>

Does anyone know how to programmatically trigger the admin save action? That is, I need to replicate clicking the 'Save' button for each simple product in the catalog.

Any help or suggestions are much appreciated!

Best Answer

Instead of actually trying to use the save action or simulate the request, I decided to look deeper into what the function does and figure out which piece I needed.

It turns out I needed to run the following on all of the affected products:

    if (Mage::app()->isSingleStoreMode()) {
        $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
    }

The products must have not been assigned correctly during my batch upload (using dataflow profiles). Here is the full script in case it is useful to anyone:

#!/usr/local/bin/php

<?php

require 'app/Mage.php';
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$products = Mage::getResourceModel('catalog/product_collection')->addAttributeToSelect('*');

foreach ($products as $product) {
    if ($product->getModshopVisibility() && !$product->isConfigurable()) {
        echo 'Product: ' . $product->getId() . ' - ' . $product->getName() . "\xA";

        if (Mage::app()->isSingleStoreMode()) {
            $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
        }

        $product->save();
    }
    else echo 'Skip ' . $product->getId() . "\xA";
}

?>
Related Topic