0

How to import color and size swatch attributes using csv.

3 Answers 3

1

Bulk update attribute options from CSV tutorial.Please click here for step by step explanation. http://www.pearlbells.co.uk/import-attribute-options-magento-2-programmatically/ enter image description here

// add new attribute options
function addNewOptions( $object_Manager, $newOptions, $storeArray ) {

$option = array();
$eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');
$option['attribute_id'] = $attribute->getAttributeId();

foreach($newOptions as $key => $value){

    $option['value'][$value][0]=$value;

    foreach($storeArray as $storeKey => $store) {
        $option['value'][$value][$storeKey] = $value;
    }   
    echo 'Added value : '.$value.PHP_EOL;
}

$eavSetup = $object_Manager->get('\Magento\Eav\Setup\EavSetup');
$eavSetup->addAttributeOption($option);

}

1
  • Is there anyway to import visual swatch value by CSV?
    – Magecode
    Dec 6, 2017 at 10:29
0

The below code I have used to add swatches. The code compare existing attribute option and add the new options with swatches images.

sample csv

The below code works for me.

use \Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');

// color = data[23]

// add bootstrap
$attrCode = 'color';
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();

$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

$formattedAttrOptions = readOptions();
$storeArr = getAllStores( $object_Manager );
addAttrsOptions( $formattedAttrOptions, $object_Manager, $storeArr, $attrCode );

function readOptions() {

$options = $alloptions = array();
$file = 'csv/all_products_2020-03-22.csv';
$handle = fopen($file, "r");
$headers = false;

if (empty($handle) === false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if (!$headers) {
            $headers[] = $data;
        } else {
            if(isset($data[23]) && ($data[23] != '')){
            $options[] = trim($data[23]);
          }
        }
    }
    fclose($handle);
}

$formattedAttrOptions = formatAttrOptions($options);
return $formattedAttrOptions;

}

function formatAttrOptions($alloptions) {

  $uniqueValues = array_unique($alloptions);
  asort($uniqueValues);
  $optionValues = array_values($uniqueValues);
  //echo '<pre>';
  //print_r($optionValues);die();
  return $optionValues;

}




 function getExistingOptions( $object_Manager , $attr ) {

$eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', $attr);
$options = $attribute->getSource()->getAllOptions();
$optionsExists = array();

foreach($options as $option) {
    $optionsExists[] = $option['label'];
}
return $optionsExists;

}

function addAttrsOptions( $formattedAttrOptions, $object_Manager, $storeArr, $attrCode) {

$newOptions = $existingOptions = array();
$existingOptions = getExistingOptions( $object_Manager, $attrCode );
$newOptions = cmpOptions( $formattedAttrOptions, $existingOptions );
$eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', $attrCode);
//echo $attrCode.PHP_EOL;die();

if( sizeof($newOptions) > 0 ) {

  $finalAttributeOptions = createOptionsArray($newOptions);
  $data = generateOptions($finalAttributeOptions, 'visual');
  $data = uploadSwatchFileToAttributeFolder( $object_Manager, $data );
  $attribute->addData($data)->save();

}
}

function generateOptions($values, $swatchType = 'visual')
{
      $i = 0;
     foreach($values as $key => $value) {
     $order["option_{$i}"] = $i;
    $optionsStore["option_{$i}"] = array(
        0 => $key, // admin
        1 => $value['label'], // default store view
    );
    $textSwatch["option_{$i}"] = array(
        1 => $value['label'],
    );
    $visualSwatch["option_{$i}"] = $value['url'];
    $delete["option_{$i}"] = '';
    $i++;
}

switch($swatchType)
{
    case 'text':
        return [
            'optiontext' => [
                'order'     => $order,
                'value'     => $optionsStore,
                'delete'    => $delete,
            ],
            'swatchtext' => [
                'value'     => $textSwatch,
            ],
        ];
        break;
    case 'visual':
        return [
            'optionvisual' => [
                'order'     => $order,
                'value'     => $optionsStore,
                'delete'    => $delete,
            ],
            'swatchvisual' => [
                'value'     => $visualSwatch,
            ],
        ];
        break;
    default:
        return [
            'option' => [
                'order'     => $order,
                'value'     => $optionsStore,
                'delete'    => $delete,
            ],
        ];
}
 }

  function uploadSwatchFileToAttributeFolder( $object_Manager, $data ) {

  $filesystem = $object_Manager->create('\Magento\Framework\Filesystem');

 // Prepare visual swatches files.
 $mediaDirectory = $filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$productMediaConfig = $object_Manager->create('\Magento\Catalog\Model\Product\Media\Config');
 $tmpMediaPath = $productMediaConfig->getBaseTmpMediaPath();
 $fullTmpMediaPath = $mediaDirectory->getAbsolutePath($tmpMediaPath);

 $driverFile = $object_Manager->create('\Magento\Framework\Filesystem\Driver\File');
 $driverFile->createDirectory($fullTmpMediaPath);
 $swatchHelper = $object_Manager->create('\Magento\Swatches\Helper\Media');

 foreach ($data as $key => $attributeOptionsData) {
  if($key == "swatchvisual" ){
      $swatchVisualFiles = isset($attributeOptionsData['value'])? $attributeOptionsData['value'] : [];
        //echo '<pre>';
        //print_r($swatchVisualFiles);die();


      foreach ($swatchVisualFiles as $index => $swatchVisualFile) {
          if(!empty($swatchVisualFile)){
              if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'swatches' . DIRECTORY_SEPARATOR . $swatchVisualFile)) {
                  $driverFile->copy(
                  __DIR__ . DIRECTORY_SEPARATOR . 'swatches' . DIRECTORY_SEPARATOR . $swatchVisualFile,
                  $fullTmpMediaPath . '/' . $swatchVisualFile
                  );

                  $newFile = $swatchHelper->moveImageFromTmp($swatchVisualFile);
                  if (substr($newFile, 0, 1) == '.') {
                      $newFile = substr($newFile, 1); // Fix generating swatch variations for files beginning with ".".
                  }
                  $swatchHelper->generateSwatchVariations($newFile);
                  $data[$key]['value'][$index] = $newFile;
              } else {
                  $data[$key]['value'][$index] = "";
              }
          }
      }
  }
 }

//echo '<pre>';
//  print_r($data);die();

  return $data;

}


 /*
Create array of options with swatch Images
*/

function createOptionsArray($newOptions) {

 $finalAttributeOptions = array();

 foreach ( $newOptions as $key => $value) {

$swatchFileName = strtolower($value).".png";
$finalAttributeOptions[$value] =  array("label" => $value, "url" => $swatchFileName );

 }
 return $finalAttributeOptions;

 // echo '<pre>';
 // print_r($finalAttributeOptions);

 }

 // Compare with Existing options

  function cmpOptions( $optionsValues, $optionsExists ) {

$newOptions = array_diff( $optionsValues, $optionsExists );
return $newOptions;

}

 // Get all stores

function getAllStores( $object_Manager ) {
$storeManager = $object_Manager->get('Magento\Store\Model\StoreManagerInterface');
$stores = $storeManager->getStores();
$storeArray[0] = "All Store Views";

foreach ($stores  as $store) {
    $storeArray[$store->getId()] = $store->getName();
}
return $storeArray;
}

enter image description here

2
  • can you post the csv file in the answer, so that I can see the format of the file? Dec 11, 2020 at 9:53
  • I don't know how to upload csv here.
    – Liz Eipe C
    Dec 11, 2020 at 12:29
0

please can you put csv or give url to a screenshot or download link

1
  • please can you put csv or give url to a screenshot or download link
    – jt9489
    Sep 15, 2022 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.