0

How to import color and size swatch attributes using csv.

0

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

}

| improve this answer | |
  • Is there anyway to import visual swatch value by CSV? – Magecode Dec 6 '17 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.

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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