How to Create Custom Swatch Attribute Programmatically in Magento 2

 


<?php


use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';


$bootstraps = Bootstrap::create(BP, $_SERVER);

$object_Manager = $bootstraps->getObjectManager();


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

$app_state->setAreaCode('frontend');


try

{

    $finalProductData = array(

        'BLKV' => array("label" => "Black", "url" => "p2.jpeg"),

        'BLKV1' => array("label" => "Black1", "url" => "p2.jpeg"),

    );


    $eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');

    $attribute = $eavConfig->getAttribute('catalog_product', 'color');


    $data = generateOptions($finalProductData, 'visual');


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


    $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']

            : [];


            foreach ($swatchVisualFiles as $index => $swatchVisualFile)

            {

                if (!empty($swatchVisualFile))

                {

                    if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $swatchVisualFile))

                    {

                        $driverFile->copy(

                            __DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $swatchVisualFile,

                            $fullTmpMediaPath . '/' . $swatchVisualFile

                        );


                        $newFile = $swatchHelper->moveImageFromTmp($swatchVisualFile);

                        if (substr($newFile, 0, 1) == '.')

                        {

                            $newFile = substr($newFile, 1); 

                        }

                        $swatchHelper->generateSwatchVariations($newFile);

                        $data[$key]['value'][$index] = $newFile;

                    }

                    else

                    {

                        $data[$key]['value'][$index] = "";

                    }

                }

            }

        }

    }


    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'], 

            );

            $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,

                    ],

                ];

        }

    }

    $attribute->addData($data)->save();

}

catch(\Exception $e)

{

    print_r($e->getMessage());

}

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2