0

I want to create custom products visual swatch attribute with custom images .

Please let me know if anyone have any example.

Thanks !!

2 Answers 2

1

Add below code in your class in which you need it.

Please make sure you have uploaded image to server before you run this code

<?php


namespace Tarun\StackOverflow\Model;

use Magento\Eav\Model\Entity;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;


/**
 * Class CreateSwatchAttributeAndUploadImages
 * @package Tarun\StackOverflow\Model\Plugin
 */
class CreateSwatchAttributeAndUploadImages
{
    /**
     * @var AttributeFactory
     */
    private AttributeFactory $attributeFactory;
    
    /**
     * @var Entity
     */
    private Entity $entity;

    /**
     * @var CollectionFactory
     */
    private CollectionFactory $groupCollectionFactory;

    /**
     * CreateSwatchAttributeAndUploadImages constructor.
     * @param AttributeFactory $attributeFactory
     * @param Entity $entity
     * @param CollectionFactory $groupCollectionFactory
     */
    public function __construct(
        AttributeFactory $attributeFactory,
        Entity $entity,
        CollectionFactory $groupCollectionFactory
    ) {
        $this->attributeFactory = $attributeFactory;
        $this->entity = $entity;
        $this->groupCollectionFactory = $groupCollectionFactory;
    }

    /**
     * @return void
     */
    public function createSwatch()
    {
        $entityTypeId = $this->entity->setType(\Magento\Catalog\Model\Product::ENTITY)->getTypeId();

        $model = $this->attributeFactory->create();
        $data = [
            "frontend_label" =>  [
                0 => "Default Frontend Attribute Label for Swatch",
                1 => "StoreView Frontend Attribute Label for Swatch"
            ],
            "frontend_input" => "select",
            "is_required" => 1,
            "update_product_preview_image" => 1,
            "use_product_image_for_swatch" => 1,
            "visual_swatch_validation" => "",
            "visual_swatch_validation_unique" => "",
            "text_swatch_validation" => "",
            "text_swatch_validation_unique" => "",
            "dropdown_attribute_validation" => "",
            "dropdown_attribute_validation_unique" => "",
            "attribute_code" => "custom_file_swatch",
            "is_global" => 0,
            "default_value_text" => "",
            "default_value_yesno" => 0,
            "default_value_date" => "",
            "default_value_datetime" => "",
            "default_value_textarea" => "",
            "is_unique" => 0,
            "is_used_in_grid" => 1,
            "is_visible_in_grid" => 1,
            "is_filterable_in_grid" => 1,
            "is_searchable" => 1,
            "search_weight" => 1,
            "is_visible_in_advanced_search" => 1,
            "is_comparable" => 1,
            "is_filterable" => 1,
            "is_filterable_in_search" => 1,
            "is_used_for_promo_rules" => 1,
            "is_html_allowed_on_front" => 1,
            "is_visible_on_front" => 1,
            "used_in_product_listing" => 1,
            "used_for_sort_by" => 1,
            "swatch_input_type" => "visual",
            "optionvisual" => [
                "order" =>  [
                    "option_0" => 1,
                    "option_1" => 2
                ],
                "value" => [
                    "option_0" =>  [
                        0 => "Admin Swatch Label for option0",
                        1 => "StoreView Swatch Label for option0"
                    ],
                    "option_1" =>  [
                        0 => "Admin Swatch Label for option1",
                        1 => "StoreView Swatch Label for option1"
                    ]
                ],
                "delete" => [
                    "option_0" => "",
                    "option_1" => ""
                ],
            ],
            "defaultvisual" =>  [
                0 => "option_0"
            ],
            "swatchvisual" =>  [
                "value" =>  [
                    "option_0" => "/s/c/Option1.jpeg", // This image must be there in your project's pub/media/attribute/swatch/s/c/Option1.jpeg
                    "option_1" => "/s/c/Option2.jpeg" // This image must be there in your project's pub/media/attribute/swatch/s/c/Option2.jpeg
                ]
            ],
            "is_pagebuilder_enabled" => 0,
            "source_model" => "",
            "backend_model" => "",
            "backend_type" => "int"
        ];

        $model->addData($data);
        $model->setEntityTypeId($entityTypeId);
        $model->setIsUserDefined(1);

        $attributeSetId = 4; //Your Attribute Set Id
        $groupCode = "product-details"; // Your Attribute Set's Group Id

        if ($attributeSetId && $groupCode) {
            // For creating product attribute on product page we need specify attribute set and group
            $groupCollection = $this->groupCollectionFactory->create()
                ->setAttributeSetFilter($attributeSetId)
                ->addFieldToFilter('attribute_group_code', $groupCode)
                ->setPageSize(1)
                ->load();

            $group = $groupCollection->getFirstItem();
            if (!$group->getId()) {
                $group->setAttributeGroupCode($groupCode);
                $group->setSortOrder(1); // Set your new group sort order here
                $group->setAttributeGroupName("New_Group"); // Set your new group name here
                $group->setAttributeSetId($attributeSetId);
                $group->save();
            }

            $model->setAttributeSetId($attributeSetId);
            $model->setAttributeGroupId($group->getId());
        }
        try {
            $model->save();
        } catch (\Exception $e) {
            dump($e->getMessage());
        }
    }
}

If this answer works as your expected, please mark it as accepted. That indicates your issue is solved and makes it easier for others with the same issue to find a verified answer. And that would be great if you click the upvote button for the answer in case you feel it is useful.

Happy Coding

6
  • You can load the swatch attribute, if you want to upload files for existing attribute. Please let me know if you need my help for that. @Mukesh Prajapati Commented Jul 25, 2023 at 12:49
  • Hello @Mukesh Prajapati, Please let me know if you face any problem or need any assistance. Your confirmation can help others to find their solution having similar issue. Commented Jul 26, 2023 at 6:30
  • Thanks you @Tarun , You answer helped me a lot . Commented Jul 26, 2023 at 9:57
  • 1
    Thank you @MukeshPrajapati, Good to know that it solved your issue. Happy Coding :) Commented Jul 26, 2023 at 11:51
  • Do you have any idea about image path ? like my images are in mymodule_mymodule/view/frontend or adminhtml/web/images/ folder then how can i assign or import in swatches? please let me know if any idea Commented Jul 26, 2023 at 14:43
1

Create one Setup/InstallData.php Like File.

<?php
namespace Vendor\Module\Setup;

use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $this->createVisualSwatchAttribute($setup);
        $setup->endSetup();
    }

    private function createVisualSwatchAttribute(ModuleDataSetupInterface $setup)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $attributeCode = 'your_attribute_code'; // Replace with your desired attribute code
        $attributeLabel = 'Your Attribute Label'; // Replace with your desired attribute label
        $attributeOptions = [
            'option_1' => ['label' => 'Option 1'],
            'option_2' => ['label' => 'Option 2'],
            // Add more options as needed...
        ];

        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            $attributeCode,
            [
                'type' => 'varchar',
                'label' => $attributeLabel,
                'input' => 'select',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
                'frontend' => '',
                'backend' => '',
                'required' => false,
                'sort_order' => 50,
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'group' => 'General',
                'option' => [
                    'values' => $attributeOptions,
                ],
                'frontend_class' => 'visual-swatch', // Important: Set this class to make it a visual swatch
                'user_defined' => true,
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'visible_in_advanced_search' => false,
                'filterable' => false,
                'searchable' => false,
                'comparable' => false,
                'unique' => false,
            ]
        );
    }
}

Place your attribute images in the following directory: "pub/media/attribute/your_attribute_code/"

pub/media/attribute/color/red.jpg pub/media/attribute/color/blue.jpg

1
  • Or you can also create it using command. Commented Jul 25, 2023 at 12:11

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.