2013-10-02 7 views
1

Je travaille actuellement sur un script d'importation personnalisé pour Magento et maintenant je veux ajouter des produits aux balises du fichier CSV. J'ai utilisé un extrait d'une autre question ici sur StackOverflow, mais pour une raison quelconque, il ne fait pas ce qui est attendu.Ajout de produits aux tags dans Magento

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

Une fois le script exécuté, le panneau d'administration montre les nouvelles balises avec un « 1 » dans la colonne « Produits », (comme prévu), mais quand je modifie rien Tag a été sélectionné.

Répondre

1

Il est difficile de trouver jusqu'à voir le code complet. Mais de toute façon ici j'ai inclus un autre morceau de code que je l'ai utilisé régulièrement et son fonctionnement bien.

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

`

Je le télécharger il y a quelques mois où certains. Configurez le module local (en réalité écraser le système principal) placez ce fichier emplacement.app \ code \ local \ Mage \ Catalogue \ Modèle \ Convert \ Adapter \ puis, Allez dans la section Admin et allez dans système-> Importer/Exporter/Avancé profil Cliquez sur Créer un nouveau profil Indiquez le nom proile comme Tag importation de produits et Actions XML * coller le code ci-dessous

<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 est le fichier de données d'importation. ce fichier contient seulement 2 champs, sku et product_tags. Ajouter les sku de votre produit et les balises correspondantes. et placez ce fichier dans votre répertoire var/import. vous pouvez voir ce fichier dans la section admin comme je l'ai mentionné ci-dessus. C'est tout ..!! Faites-moi savoir si vous avez un problème.

+0

On m'a appris à ne pas éditer le Core de Magento, pour éviter d'endommager la boutique en ligne dès que l'installation de Magento est mise à jour. Mais merci, je vais regarder à travers ce code. – plvdmeer

Questions connexes