0

我在 magento 中以编程方式运行更新产品的脚本。当我们添加产品时它工作正常,但是当我们使用此脚本和产品 csv 文件更新产品时,第一行产品状态未在 magento 管理面板中更新。

这是更新函数的代码——

public function updateProduct($importData,$feed_category,$feed_margin)
    {

        $sku = trim($importData['sku']);
        $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

        if($this->getBatchParams('mark_up') == '') {
            $mark_up = '15';
        } else {
            $mark_up = $this->getBatchParams('mark_up');
        }

        if($this->getBatchParams('mark_up_type') == '') {
            $mark_up_type = 'percent';
        } else {
            $mark_up_type = $this->getBatchParams('mark_up_type');
        }

        $prprice = $importData['your_buy_ex_gst'];

        if($mark_up_type=='percent'){
            $prprice = ($prprice/(1-($feed_margin/100)));
        }
        else{
            $prprice = $prprice+$feed_margin;   
        }

        #Set attribute set id
        $productAttributeSets = $this->getProductAttributeSets ();
        if(!isset($importData ['attribute_set'])){
            if($this->getBatchParams('attribute_set') == '') {
                $importData ['attribute_set'] = 'data_feed';
            } else {
                $importData ['attribute_set'] = $this->getBatchParams('attribute_set');
            }
        }
        if(empty($importData ['attribute_set'] ) || ! isset ( $productAttributeSets [$importData ['attribute_set']] )) {
                $value = isset ( $importData ['attribute_set'] ) ? $importData ['attribute_set'] : '';
                $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set' );
                Mage::throwException ( $message );
            }
        $product->setAttributeSetId ( $productAttributeSets [$importData ['attribute_set']]);
        #END : Set attribute set id

        $product->setPrice($prprice);
        $product->setName($importData['name']);
        $product->setDescription($importData['description']);
        $product->setShortDescription($importData['description']);
        $product->setStatus(1);

        //$product->setData ($field, $setValue)

        #Adding the image to media gallery#
        $importData['image_large']=trim($importData['image_large']);
        if($importData['image_large'] != '')
        {
            $image_url  = $importData['image_large']; //get external image url from csv
            /*Checking if the image is real or corrupt*/
            list($width, $height, $type, $attr) = @getimagesize($image_url);
            if(isset($width) && $width!='' && isset($height) && $height!='' ){  
                $image_type = substr(strrchr($image_url,"."),1); //find the image extension
                $filename   = md5($image_url . $importData['sku']).'.'.$image_type; //give a new name, you can modify as per your requirement
                $filepath   = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/
                file_put_contents($filepath, file_get_contents(trim($image_url))); //store the image from external url to the temp storage folder
                /*check again for corrupt image*/
                list($width_dk, $height_dk, $type_dk, $attr) = @getimagesize($filepath);
                if( isset($width_dk) && $width_dk!='' && isset($height_dk) && $height_dk!=''){  

                    /* Start deleting the old images from media gallery before insert */
                    if ($product->getId()){
                        $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
                        $items = $mediaApi->items($product->getId());
                        foreach($items as $item)
                        $mediaApi->remove($product->getId(), $item['file']);
                    }
                    /* End deleting the old images from media gallery before insert */

                    $mediaAttribute = array (
                            'thumbnail',
                            'small_image',
                            'image'
                    );
                    $product->addImageToMediaGallery($filepath, $mediaAttribute, true, false);

                } else {
                    /*One more try to get the imag right*/
                    @unlink($filepath);
                    $image_type = substr(strrchr($image_url,"."),1); 
                    $filename   = md5($image_url . $importData['sku']).'.'.$image_type; 
                    $filepath   = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; 
                    file_put_contents($filepath, file_get_contents(trim($image_url)));  
                    list($width_dk, $height_dk, $type_dk, $attr) = @getimagesize($filepath);
                    if( isset($width_dk) && $width_dk!='' && isset($height_dk) && $height_dk!=''){
                        /* Start deleting the old images from media gallery before insert */
                        if ($product->getId()){
                            $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
                            $items = $mediaApi->items($product->getId());
                            foreach($items as $item)
                            $mediaApi->remove($product->getId(), $item['file']);
                        }
                        /* End deleting the old images from media gallery before insert */

                        $mediaAttribute = array (
                                'thumbnail',
                                'small_image',
                                'image'
                        );
                        $product->addImageToMediaGallery($filepath, $mediaAttribute, true, false);
                    }
                }
            } 
        }
        #Adding the image to media gallery#

        #Attribute mapping#
            foreach($importData as $field => $value){
            // if (in_array($field, $this->_inventorySimpleFields)) {works only for old version )
            if (in_array ( $field, $this->_inventoryFields )) {
                continue;
            }
            if (in_array ( $field, $this->_imageFields )) {
                continue;
            }

            $attribute = $this->getAttribute ( $field );
            if (! $attribute) {
                continue;
            }

            $isArray = false;
            $setValue = $value;

            if($attribute->getFrontendInput () == 'multiselect'){
                $value = split ( self::MULTI_DELIMITER, $value );
                $isArray = true;
                $setValue = array();
            }

            if($value && $attribute->getBackendType () == 'decimal'){
                $setValue = $this->getNumber ( $value );
            }

            if($value && $attribute->getBackendType () == 'datetime'){
                $setValue= date('Y-m-j', strtotime($value));
            }


            if($attribute->usesSource ()){
                $options = $attribute->getSource ()->getAllOptions ( false );

                if ($isArray) {
                    foreach ( $options as $item ) {
                        if (in_array ( $item ['label'], $value )) {
                            $setValue [] = $item ['value'];
                        }
                    }
                } else {
                    $setValue = null;
                    foreach ( $options as $item ) {
                        if ($item ['label'] == $value) {
                            $setValue = $item ['value'];
                        }
                    }
                }
            }
            $product->setData ( $field, $setValue );
        }

        #Getting the store#
        if (empty ( $importData ['store'] )) {
            if($this->getBatchParams('store') == '') {
                $param_store = '2';
            } else {
                $param_store = $this->getBatchParams('store');
            }
            if (! is_null ( $param_store )) {
                    $store = Mage::app()->getStore( $param_store );
            } else {
                    $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not defined', 'store' );
                    Mage::throwException ( $message );
            }
        } else {
                $store = $this->getStoreByCode ($importData['store']);
        }

        if($store === false){
            $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, store "%s" field not exists', $importData['store']);
            Mage::throwException ($message);
        }
        #END : Getting the store#

        //// Para importar categorias 
        $currentCatIds = $product->getCategoryIds();
        if(is_array($currentCatIds) && count($currentCatIds)>0){
            $cats = implode(',',$currentCatIds);        
            $cats = $cats.','.$feed_category;
            $product->setCategoryIds($cats);
        }
        else{
            $product->setCategoryIds($feed_category);
        }
        ////

        $product->setWeight($importData['weight']);

        $productId = $product->getId();
        $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
        $stockItemId = $stockItem->getId();
        $stockItem->setData('manage_stock', 1);

        if($importData['weight'] == '' || $importData['weight'] == '0') {
            $stockItem->setData('is_in_stock', 0);
        } else {
            $stockItem->setData('is_in_stock', 1);
        }

        $stockItem->setData('qty', $importData['quantity']);
        $stockItem->save();

        try { 
            $product->save();
            //echo $importData['sku']. ' - updated' .'<br/>';
        }
        catch (Exception $ex) {
            echo $ex."<br><br><br>";
        }   


    }
4

2 回答 2

0

在这里查看我的答案:Magento 导入带有图像的产品

第一行包含关键字(或字段名称)。

于 2013-04-29T20:26:33.697 回答
0

检查您的 csv 或 txt 文件产品状态值。启用=1 禁用=2。和字段名称“状态”(csv 标题)。(这是针对 Magento 1.4 的。)

例子。

“sku”“状态”

"Product1" "1(用于启用产品)"

"Product2" "2(用于禁用产品)"

如果您有任何问题,请向我展示您的示例 csv 文件。

于 2013-05-07T21:36:53.810 回答