以编程方式将产品添加到Magento中的标签

时间:2013-10-02 08:59:50

标签: php magento magento-1.7

我目前正在为Magento制作自定义导入脚本,现在我想从CSV文件中将标签添加到标签中。我在StackOverflow上使用了另一个问题的片段,但由于某种原因它没有达到预期的效果。

function addTag($bundleProductId, $tagArray) {
    $tags = explode(',', $tagArray);
    array_walk($tags, 'trim_value');

    $customerId = NULL;
    $storeId = Mage::app()->getStore()->getId();
    $productId = $bundleProductId;

    $tagModel = Mage::getModel('tag/tag');
    //$tagModel->loadByName($tagName); // if not using a loop
    foreach ($tags as $tagName) {
    $tagModel->unsetData()->loadByName($tagName); //if using a loop 

        if (!$tagModel->getId()) {
             $tagModel->setName($tagName)
                  ->setFirstCustomerId($customerId)
                  ->setFirstStoreId($storeId)
                  ->setStatus($tagModel->getPendingStatus())
                  ->save();
        }
   $relationStatus = $tagModel->saveRelation($productId, $customerId, $storeId);
    }
}

脚本运行后,管理面板会在“产品”列中显示“1”的新标签(正如预期的那样),但是当我编辑标签时,没有选择任何内容。

1 个答案:

答案 0 :(得分:1)

在查看完整代码之前很难找到。但无论如何,我已经包含了另外一些代码,我已经定期使用它并且工作正常。

<?php

class Mage_Catalog_Model_Convert_Adapter_ProductTags extends Mage_Catalog_Model_Convert_Adapter_Product {


public function saveRow(array $importData) {
    $product = $this->getProductModel ();
    $product->setData ( array () );
    if ($stockItem = $product->getStockItem ()) {
        $stockItem->setData ( array () );
    }
    $product = Mage::getModel('catalog/product');
    $productId='';
    $productId = $product->getIdBySku($importData['sku']);  
    $tagNames = $importData['product_tags'];
    if (empty ( $importData ['sku'] )) {
        $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not defined', 'sku' );
        Mage::throwException ( $message );
    }       
    if ( !$productId ) {
        $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not Valid Sku', $importData['sku'] );
        Mage::throwException ( $message );
    }
    if(strlen($tagNames) && $productId) {
        $session = Mage::getSingleton('catalog/session');
        $product = Mage::getModel('catalog/product')
            ->load($productId);
            $productId =$product->getId();
        if(!$product->getId()){
           $message = Mage::helper ( 'catalog' )->__ ( 'Skip import row, required field "%s" not valid', 'sku' );
            Mage::throwException ( $message );
        } else {
            try {
              $customerId = NULL;
              $storeId = 1;
              $tagModel='';                 
              $counter = new Varien_Object(array(
                        "new" => 0,
                        "exist" => array(),
                        "success" => array(),
                        "recurrence" => array())
                        );                  
               $tagModel = Mage::getModel('tag/tag');
               $tagRelationModel = Mage::getModel('tag/tag_relation');
               $tagNamesArr = $this->_cleanTags($this->_extractTags($tagNames));
               foreach ($tagNamesArr as $tagName) {
                    $tagModel->unsetData()
                            ->loadByName($tagName)
                            ->setName($tagName)
                            ->setFirstCustomerId($customerId)
                            ->setFirstStoreId($storeId)
                            ->setStatus(1)
                            ->save();

                    $tagRelationModel->unsetData()
                        ->setStoreId($storeId)
                        ->setProductId($productId)
                        ->setCustomerId($customerId)
                        ->setActive(Mage_Tag_Model_Tag_Relation::STATUS_ACTIVE)
                        ->setCreatedAt( $tagRelationModel->getResource()->formatDate(time()) );

                    if (!$tagModel->getId()) {  
                        $tagModel->setName($tagName)
                            ->setFirstCustomerId($customerId)
                            ->setFirstStoreId($storeId)
                            ->setStatus($tagModel->getPendingStatus())
                            ->save();
                        $relationStatus = $tagModel->saveRelation($productId, $customerId, $storeId);
                        $counter[$relationStatus][] = $tagName; 
                        $tagRelationModel->setTagId($tagModel->getId())->save();
                        $counter->setNew($counter->getNew() + 1);
                    }
                    else { 
                        $tagStatus = $tagModel->getStatus();
                        $tagRelationModel->setTagId($tagModel->getId());
                        $relationStatus = $tagModel->saveRelation($productId, $customerId,'');
                        $counter[$relationStatus][] = $tagName; 
                        switch($tagStatus) {
                            case $tagModel->getApprovedStatus(): 
                                if($this->_checkLinkBetweenTagProduct($tagRelationModel)) { 
                                    $relation = $this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel);
                                    if ($relation->getId()) {
                                        if (!$relation->getActive()) {
                                            $tagRelationModel
                                                ->setId($relation->getId())
                                                ->save();
                                        }
                                    } 
                                    else { 
                                        $tagRelationModel->save();
                                    }                                       
                                    $counter->setExist(array_merge($counter->getExist(), array($tagName)));
                                } 
                                else { 
                                    $tagRelationModel->save(); 
                                    $counter->setSuccess(array_merge($counter->getSuccess(), array($tagName)));
                                }
                                break;
                            case $tagModel->getPendingStatus(): 
                                $relation = $this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel);
                                if ($relation->getId()) {
                                    if (!$relation->getActive()) {
                                        $tagRelationModel
                                            ->setId($relation->getId())
                                            ->save();
                                    }
                                } 
                                else {
                                    $tagRelationModel->save();
                                }
                                $counter->setNew($counter->getNew() + 1);
                                break;
                            case $tagModel->getDisabledStatus():
                                if($this->_checkLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)) {
                                    $counter->setRecurrence(array_merge($counter->getRecurrence(), array($tagName)));
                                } 
                                else {
                                    $tagModel->setStatus($tagModel->getPendingStatus())->save();
                                    $tagRelationModel->save();
                                    $counter->setNew($counter->getNew() + 1);
                                }
                            break;
                        }
                    }
                }
            } catch (Exception $e) {
                Mage::logException($e);
                $message='Unable to save tag(s).';
                Mage :: throwException( $e.$message );
            }
        }
    }               
    return true;
}

   protected function _getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel){
        return Mage::getModel('tag/tag_relation')->loadByTagCustomer(
            $tagRelationModel->getProductId(),
            $tagModel->getId(),
            $tagRelationModel->getCustomerId(),
            $tagRelationModel->getStoreId()
          );
    }

     protected function _checkLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel){
        return (count($this->_getLinkBetweenTagCustomerProduct($tagRelationModel, $tagModel)
            ->getProductIds()) > 0);
    }   
    protected function _checkLinkBetweenTagProduct($tagRelationModel){      
        $customerId = $tagRelationModel->getCustomerId();
        $tagRelationModel->setCustomerId(null);
        $res = in_array($tagRelationModel->getProductId(), $tagRelationModel->getProductIds());
        $tagRelationModel->setCustomerId($customerId); 
        return $res;
    }
    protected function _cleanTags(array $tagNamesArr){
        foreach( $tagNamesArr as $key => $tagName ){
            $tagNamesArr[$key] = trim($tagNamesArr[$key], '\'');
            $tagNamesArr[$key] = trim($tagNamesArr[$key]);
            if( $tagNamesArr[$key] == '' ) {
                unset($tagNamesArr[$key]);
            }
        }
        return $tagNamesArr;
    }
    protected function _extractTags($tagNamesInString){
        return explode("\n", preg_replace("/(\'(.*?)\')|(\s+)/i", "$1\n", $tagNamesInString));
    }   
    protected function userCSVDataAsArray($data) {
        return explode ( ',', str_replace ( " ", "", $data ) );
    }
    protected function skusToIds($userData, $product) {
        $productIds = array ();
        foreach ( $this->userCSVDataAsArray ( $userData ) as $oneSku ) {
            if (($a_sku = ( int ) $product->getIdBySku ( $oneSku )) > 0) {
                parse_str ( "position=", $productIds [$a_sku] );
            }
        }
        return $productIds;
    }

//// Para importar categorias
    protected $_categoryCache = array ();
    protected function _addCategories($categories, $store) {
        $rootId = $store->getRootCategoryId ();
        if (! $rootId) {
            return array ();
        }
        $rootPath = '1/' . $rootId;
        if (empty ( $this->_categoryCache [$store->getId ()] )) {
            $collection = Mage::getModel ( 'catalog/category' )->getCollection ()->setStore ( $store )->addAttributeToSelect ( 'name' );
            $collection->getSelect ()->where ( "path like '" . $rootPath . "/%'" );
            foreach ( $collection as $cat ) {
                $pathArr = explode ( '/', $cat->getPath () );
                $namePath = '';
                for($i = 2, $l = sizeof ( $pathArr ); $i < $l; $i ++) {
                    $name = $collection->getItemById ( $pathArr [$i] )->getName ();
                    $namePath .= (empty ( $namePath ) ? '' : '/') . trim ( $name );
                }
                $cat->setNamePath ( $namePath );
            }               
            $cache = array ();
            foreach ( $collection as $cat ) {
                $cache [strtolower ( $cat->getNamePath () )] = $cat;
                $cat->unsNamePath ();
            }
            $this->_categoryCache [$store->getId ()] = $cache;
        }
        $cache = & $this->_categoryCache [$store->getId ()];            
        $catIds = array ();
        foreach ( explode ( ',', $categories ) as $categoryPathStr ) {
            $categoryPathStr = preg_replace ( '#s*/s*#', '/', trim ( $categoryPathStr ) );
            if (! empty ( $cache [$categoryPathStr] )) {
                $catIds [] = $cache [$categoryPathStr]->getId ();
                continue;
            }
            $path = $rootPath;
            $namePath = '';
            foreach ( explode ( '/', $categoryPathStr ) as $catName ) {
                $namePath .= (empty ( $namePath ) ? '' : '/') . strtolower ( $catName );
                if (empty ( $cache [$namePath] )) {
                    $cat = Mage::getModel ( 'catalog/category' )->setStoreId ( $store->getId () )->setPath ( $path )->setName ( $catName )->// comment out the following line if new categories should stay inactive
                    setIsActive ( 1 )->save ();
                    $cache [$namePath] = $cat;
                }
                $catId = $cache [$namePath]->getId ();
                $path .= '/' . $catId;
            }
            if ($catId) {
                $catIds [] = $catId;
            }
        }
        return join ( ',', $catIds );
    }
}   

`

几个月前我从某个地方下载它。配置本地模块(实际上覆盖核心系统)将此文件放在此location.app \ code \ local \ Mage \ Catalog \ Model \ Convert \ Adapter \ then, 转到管理员部分,然后转到system-&gt;导入/导出/高级配置文件     单击“创建新配置文件”     将proile名称命名为Product Tag Import     并在Actions XML *中粘贴代码

<action type="dataflow/convert_adapter_io" method="load"> 
                <var name="type">file</var> 
                <var name="path">var/import</var> 
                <var name="filename"><![CDATA[tag_file.csv]]></var> 
                <var name="format"><![CDATA[csv]]></var> 
            </action> 

            <action type="dataflow/convert_parser_csv" method="parse"> 
                <var name="delimiter"><![CDATA[,]]></var> 
                <var name="enclose"><![CDATA["]]></var> 
                <var name="fieldnames">true</var> 
                <var name="store"><![CDATA[0]]></var> 
                <var name="number_of_records">1</var> 
                <var name="decimal_separator"><![CDATA[.]]></var> 
                <var name="adapter">catalog/convert_adapter_ProductTags</var> 
                <var name="method">parse</var> 
            </action>

tag_file.csv是导入数据的文件。这个文件只包含2个字段,sku和product_tags。 添加产品sku和相应的标签。并将该文件放在var / import目录中。如上所述,您可以在管理部分中查看此文件。而已 ..!!如果有任何问题,请告诉我。