Magento – Magento 2: How to quickly import the color swatches

attributescolor-swatchesmagento2

I've more than 50k attributes to apply the color swatches, I'd like to know if there are different method more easy or fast than the manual process?

Best Answer

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;

}[![enter image description here][1]][1]

 // 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;
}
Related Topic