CSV第一行产品状态在以编程方式更新产品后未在magento中更新

时间:2013-04-29 12:05:13

标签: php magento magento-1.7

我在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>";
        }   


    }

2 个答案:

答案 0 :(得分:0)

在此处查看我的答案:Magento import products with images

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

答案 1 :(得分:0)

检入您的csv或txt文件产品状态值。 enable = 1 disable = 2。和字段名称“status”(csv标题)。 (这适用于Magento 1.4。)

实施例

“SKU”, “状态”

“Product1”“1(对于启用产品)”

“Product2”“2(禁用产品)”

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

相关问题