1

I'm trying to make clones of a product, however my action for this is executed repeatedly until I log out from admin. This action is executed by pressing a button placed in each row of a custom grid. why is this happening and what is the solution?

This is clone action in Mymodule_adminhtml_PlantgridController

public function CloneAction()
{

    $data = $this->getRequest()->getParams();
    if($data['id'] == null || $data['cloneamount'] == null){
        return;
    }


    $line = date( "Y年m月d日 H時i分s秒" ).date_default_timezone_get().'  id:'.$data['id'].'  複製数:'.$data['cloneamount'];
    $baseDir = Mage::getBaseDir();
    $logfile = fopen($baseDir.DS.'var'.DS.'ClonePlant.txt',"a");
    fwrite($logfile,$line.PHP_EOL);
    fclose($logfile);

    $inputMessage = 'Hello World';


    $session = Mage::getSingleton('adminhtml/session');

    $lasttime = 0;
    $line = '';
    Mage::log($session->getData());
    if($session->getData('clone'.$data['id']) == null){
        $session->setData('clone'.$data['id'],time());
        $line = '1 ';
    }else{
        $lasttime = $session->getData('clone'.$data['id']);
        $line = '2 ';
        if((time() - $lasttime) < 180){
            $line = '3 ';
            return;
        }
    }
    Mage::log($session->getData());
    Mage::log(time());
    //$line .= $session->getData('clone'.'2948');
    //$line .= '#'.$session->getData('clone'.'29428').'#';

    $lasttime2 = $session->getData('clone'.$data['id']);
    $line .= '成功'.$lasttime2.' '.date( "Y年m月d日 H時i分s秒" ).date_default_timezone_get().'  id:'.$data['id'].'  複製数:'.$data['cloneamount'];
    $baseDir = Mage::getBaseDir();
    $logfile = fopen($baseDir.DS.'var'.DS.'ClonePlant.txt',"a");
    fwrite($logfile,$line.PHP_EOL);
    fclose($logfile);

    $csv = Mage::helper('mymodule/PrintLabelCsv');

    $product = Mage::getModel('catalog/product');
    $product2 = Mage::getModel('catalog/product');

    $oldnameeng = mb_convert_kana($product2->setStoreId(2)->load($data['id'])->getName(), 's');

    $productorig = $product2->setStoreId(1)->load($data['id']);
    $_product = $product->load($data['id']);

    $rmks = $productorig->getCollnumber()
        . '/'
        . $productorig->getResource()->getAttribute('plantremarks')->getFrontend()->getValue($productorig)
        . '/'
        . $productorig->getData('otherremarks');
    $rmks = str_replace(',', '/', $rmks);



    $oldsku = $productorig->getSku();


    $flag = false;
        if (substr($oldsku, 0, 6) == 0) {
            $flag = true;
    }
    $oldname = str_replace(' ', ' ', $productorig->getName());
    $oldnames = array($oldname, $oldnameeng);
    $sname = $productorig->getScientificname();
    if (!(substr($productorig->getSku(), 0, 6) == 0)) {
        //$csv->addData($sname, $oldname, $rmks);
    }

    if (is_numeric($data['cloneamount']) && $oldname != null) {
        if ($data['cloneamount'] > 99) {
            $data['cloneamount'] = 99;
        }
        for ($i = 0; $i < $data['cloneamount']*1; $i++) {
            $clone = $_product->duplicate();

            $newsku = str_pad($clone->getId(), 6, "0", STR_PAD_LEFT) . substr($oldsku, 6);


            $newnames = array();
            for ($n = 0; $n < count($oldnames); $n++) {
                //$newnames[$n] = trim($oldnames[$n]);
                $newnames[$n] = rtrim($oldnames[$n],' 0..9');
                //$newnames[$n] = mb_substr($oldnames[$n], 0, strrpos($oldnames[$n], ' '));
                $newnames[$n] .= ' ' . $clone->getId();
            }

            $clone->setIsMassupdate(true)
                ->setExcludeUrlRewrite(true)
                ->setSku($newsku)
                ->setName($newnames[0])
                ->setUrlKey($newsku)
                ->setNewsFromDate(date('m/d/Y', strtotime('now')))
                ->setNewsToDate(date('m/d/Y', strtotime('+1 month')))
                ->setImage(null)
                ->setSmallImage(null)
                ->setThumbnail(null)
                ->setMediaGallery(array());


            try {
                $clone->getResource()->save($clone);
                $new_product = $product->load($clone->getId());
                $new_product->save();

Mage_Catalog_Model_Product_Status::STATUS_ENABLED);


                //remove images.
                $mediaApi = Mage::getModel('catalog/product_attribute_media_api');
                $items = $mediaApi->items($clone->getId());
                foreach ($items as $item) {
                    $mediaApi->remove($clone->getId(), $item['file']);
                }

                //set qty.
                $stockItem = Mage::getModel('cataloginventory/stock_item')
                    ->loadByProduct($clone->getId());
                $stockItem->setData('is_in_stock', 1);
                $stockItem->setData('qty', 1);
                $stockItem->save();

            } catch (Exception $e) {
                Mage::log($e->getMessage());

            }
            $csv->addData($sname, $newnames[0], $rmks);


Mage_Catalog_Model_Product_Status::STATUS_DISABLED);

        }
        if ($flag) {
            $opro = Mage::getModel('catalog/product');
            $opro->load($data['id'])->delete();
        }
        $processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
        $processes->walk('reindexAll');

        $filename = 'Label.csv';
        $csvtest = $csv->getCsv();
        $this->_prepareDownloadResponse($filename, $csvtest);

    }
}

clone action is called from a button placed in each row of a grid.

class Mymodule_Block_Template_Grid_Renderer_Cloneplant extends     Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{

public function render(Varien_Object $row)
{
    $value = $row->getData($this->getColumn()->getIndex());
    $popup = 'onSubmit="return confirm('."'Are you sure?'".');"';
    $formname = 'cloneform'.$row->getId();
    $formurl = $this->getUrl('*/*/clone', array('id' => $row->getId()));
    return '<form method="get" action="'.$formurl.'" name="'.$formname
    .'" style="color:red;"'.$popup.' ><input type="number" name="cloneamount"
     min="0" max="99" required >
    <input type="submit" value="Clone">
    </form>';
}

}
  • Can you get duplicate products with this code? – Jaimin Sutariya Feb 6 '17 at 17:44
  • What about redirecting to the previous page at the end of the method? – bassplayer7 Feb 6 '17 at 17:57
  • @JaiminSutariya yes, it does. the problem is that it creates clones way more than I want it to. – seitymo Feb 7 '17 at 2:03
  • @bassplayer7 I tried, however this action seems to be looping in the background. Even though I go to another part of the admin, it keeps duplicating the product... – seitymo Feb 7 '17 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.