Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Steps to Add Dynamic Field in Product Create/Edit Form

Vinh Jacker | 08-28-2024

Steps to Add Dynamic Field in Product Create/Edit Form Steps to Add Dynamic Field in Product Create/Edit Form

The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

Adding dynamic fields to the product create/edit form in Magento 2 allows you to customize your product attributes and forms according to specific business needs. By incorporating dynamic fields into the admin product edit form, you can customize product information easily without modifying the core code.

In this article, we’ll walk through the detailed steps to add a dynamic field in the product create/edit form. Let’s dive in!

Step 1: Module Setup

Make sure you have the necessary module installed in your Magento 2 version.

Step 2: Create A Product Attribute

Create a file named UpgradeProductAttr.php at the following path app/code/Mageplaza/CustomAttibute/Setup/Patch/Data/UpgradeProductAttr.php. This file will be executed when you run the setup.

<?php
namespace Mageplaza\CustomAttibute\Setup\Patch\Data;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Type;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Downloadable\Model\Product\Type as DownloadableType;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Model\Entity\Attribute\Source\Boolean;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Mageplaza\CustomAttibute\Model\Attribute\Backend\Pattern;
use Mageplaza\CustomAttibute\Model\Config\Source\CustomerGroups;


/**
* Class UpgradeProductAttr
* Mageplaza\CustomAttibute\Setup\Patch\Data
*/
class UpgradeProductAttr implements
   DataPatchInterface,
   PatchRevertableInterface
{
   /**
    * @var ModuleDataSetupInterface $moduleDataSetup
    */
   private $moduleDataSetup;


   /**
    * @var EavSetupFactory $eavSetupFactory
    */
   private $eavSetupFactory;


   /**
    * @var $savePattern
    */
   private $savePattern = Pattern::class;


   /**
    * @var $typeBoolean
    */
   private $typeBoolean = Boolean::class;


   /**
    * UpgradeProductAttr constructor.
    * @param ModuleDataSetupInterface $moduleDataSetup
    * @param EavSetupFactory $eavSetupFactory
    */
   public function __construct(
       ModuleDataSetupInterface $moduleDataSetup,
       eavSetupFactory $eavSetupFactory
   ) {
       $this->moduleDataSetup = $moduleDataSetup;
       $this->eavSetupFactory = $eavSetupFactory;
   }


   /**
    * Apply
    *
    * @return void
    * @throws \Magento\Framework\Exception\LocalizedException
    * @throws \Magento\Framework\Validator\ValidateException
    */
   public function apply()
   {
       $setup = $this->moduleDataSetup;
       /** @var EavSetup $eavSetup */
       $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);


       $eavSetup->addAttribute(
           Product::ENTITY,
           'mp_rw_customer_group',
           array_merge(
               $this->getDFOptionsProduct(),
               [
                   'type'    => 'text',
                   'backend' => $this->savePattern,
                   'label'   => 'Customer Group(s)',
                   'input'   => 'multiselect',
                   'class'   => 'mp_rw_customer_group',
                   'source'  => CustomerGroups::class,
                   'default' => null
               ]
           )
       );
   }


   /**
    * @return array
    */
   protected function getDFOptionsProduct()
   {
       $productTypes = [
           Type::TYPE_SIMPLE,
           Type::TYPE_VIRTUAL,
           DownloadableType::TYPE_DOWNLOADABLE,
           Configurable::TYPE_CODE
       ];


       return [
           'group'                   => 'Sell Product By Points',
           'global'                  => ScopedAttributeInterface::SCOPE_GLOBAL,
           'visible'                 => true,
           'required'                => false,
           'user_defined'            => false,
           'searchable'              => false,
           'filterable'              => false,
           'comparable'              => false,
           'visible_on_front'        => false,
           'used_in_product_listing' => true,
           'unique'                  => false,
           'frontend'                => '',
           'apply_to'                => join(',', $productTypes)
       ];
   }


   /**
    * @inheritdoc
    */
   public function revert()
   {
   }


   /**
    * @inheritdoc
    */
   public function getAliases()
   {
       return [];
   }


   /**
    * @inheritdoc
    */
   public static function getDependencies()
   {
       return [];
   }


   /**
    * @return string
    */
   public static function getVersion()
   {
       return '1.0.0';
   }
}

Create a file named CustomerGroups in the path: \Mageplaza\CustomAttibute\Model\Config\Source\CustomerGroups. This file will define the source of the customer group.

<?php

namespace Mageplaza\CustomAttibute\Model\Config\Source;
use Magento\Customer\Model\ResourceModel\Group\Collection;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

/**
* Class CustomerGroups
* Mageplaza\CustomAttibute\Model\Config\Source
*/
class CustomerGroups extends AbstractSource
{
   /**
    * @var Collection
    */
   private $collection;


   /**
    * CustomerGroups constructor.
    *
    * @param Collection $collection
    */
   public function __construct(Collection $collection)
   {
       $this->collection = $collection;
   }

   /**
    * @return array
    */
   public function toOptionArray()
   {
       $this->_options[] = [
           'label' => __('-- Please Select --'),
           'value' => '999',
       ];


       foreach ($this->collection->toOptionArray() as $item) {
           $this->_options[] = [
               'label' => __($item['label']),
               'value' => $item['value'],
           ];
       }


       return $this->_options;
   }


   /**
    * Get all options
    *
    * @return array
    */
   public function getAllOptions()
   {
       $this->_options[] = [
           'label' => __('-- Please Select --'),
           'value' => '999',
       ];


       foreach ($this->collection->toOptionArray() as $item) {
           $this->_options[] = [
               'label' => __($item['label']),
               'value' => $item['value'],
           ];
       }


       return $this->_options;
   }
}


Step3: Run php/bin magento setup:upgrade

After completing these steps ablove, run php/bin magento setup:upgrade to apply the changes. You need to have a new group name is Sell Product By Points and new field called Customer Group(s) with a multiple select type.

Let’s check the result.

Dynamic field in product create/edit form

Conclusion

By following the steps above, you can successfully add a dynamic field to the product create/edit form in Magento 2. This customization allows you to collect specific information from your customers, enhancing their shopping experience.

Remember to test thoroughly to ensure the dynamic field behaves as expected. If you need further assistance or have any questions, feel free to ask!

Related Post

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services