简体   繁体   English

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

[英]Programmatically adding products to tags in Magento

I'm currently working on a custom import script for Magento and now I want to add products to the Tags from the CSV file. 我目前正在为Magento开发自定义导入脚本,现在我想将产品从CSV文件添加到标签中。 I've used a snippet from another question here on StackOverflow, but for some reason it doesn't do what is expected. 我在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);
    }
}

After the script has run, the Admin Panel shows the new tags with a "1" in the "Products" column, (as expected,) but when I edit the Tag nothing has been selected. 脚本运行后,“管理面板”在“产品”列中显示带有“ 1”的新标签(如预期),但是当我编辑标签时,未选择任何内容。

Its hard to find until to see full code. 很难找到完整的代码。 But anyway here I have include another bit of code that I have used it regularly and its working fine. 但是无论如何,我还是包含了我经常使用的其他代码,并且可以正常工作。

<?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 );
    }
}   

` `

I download it few months ago from some where. 我几个月前从某个地方下载了它。 Configure local module ( actually overwrite the core system ) place this file this location.app\\code\\local\\Mage\\Catalog\\Model\\Convert\\Adapter\\ then, Go to Admin section and go to system->Import/Export/Advanced Profile Click on Create New profile Give proile name as Product Tag Import and in Actions XML * paste below code 配置本地模块(实际上覆盖核心系统),将此文件放置在此位置。app\\ code \\ local \\ Mage \\ Catalog \\ Model \\ Convert \\ Adapter \\,然后转到Admin部分,然后转到system-> Import / Export / Advanced Profile单击“创建新配置文件”,将产品名称命名为“产品标签导入”,并在“操作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 is the file of your import data. tag_file.csv是导入数据的文件。 this file contains just 2 fields, sku and product_tags. 该文件仅包含2个字段sku和product_tags。 Add your product sku's and corresponding tags. 添加您的产品sku和相应的标签。 and put that file in your var/import directory. 并将该文件放在var / import目录中。 you can view this file in admin section as I mentioned above. 您可以如上所述在管理部分中查看此文件。 Thats it ..!! 而已 ..!! Let me know if have any problem. 让我知道是否有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM