TransWikia.com

Magento2 - How to add custom product attribute of type date range ie to date and from date

Magento Asked by Kévin Vuillemin on January 8, 2021

I would like to add an attribute with two datetime like : “Set Product as New From” :

enter image description here

Because I want show products with “good deal” or “our selection” for example.

Can you help me ? thank you =)

2 Answers

In order to create a data range attribute, you have to create two attributes first.

in the Setup schema file you have to create a date attribute like below.

InstallData.php

if (!$this->attributeInfo->getAttributeId(MagentoCatalogModelProduct::ENTITY, self::PRESALE_START)) {
        $eavSetup->addAttribute(
            MagentoCatalogModelProduct::ENTITY,
            self::PRESALE_START,
            [
                'type' => 'datetime',
                'backend' => '',
                'frontend' => '',
                'label' => 'Presale Start',
                'input' => 'date',
                'class' => '',
                'group' => 'Delivery Date',
                'global' => ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '',
                'searchable' => true,
                'filterable' => true,
                'comparable' => true,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'sort_order' => '70',
                'source' => '',
                'is_used_in_grid' => true,
                'is_visible_in_grid' => true,
                'is_filterable_in_grid' => true,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable',
            ]
        );
    }

    if (!$this->attributeInfo->getAttributeId(MagentoCatalogModelProduct::ENTITY, self::PRESALE_END)) {
        $eavSetup->addAttribute(
            MagentoCatalogModelProduct::ENTITY,
            self::PRESALE_END,
            [
                'type' => 'datetime',
                'backend' => '',
                'frontend' => '',
                'label' => 'Presale End',
                'input' => 'date',
                'class' => '',
                'group' => 'Delivery Date',
                'global' => ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '',
                'searchable' => true,
                'filterable' => true,
                'comparable' => true,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'source' => '',
                'sort_order' => '80',
                'is_used_in_grid' => true,
                'is_visible_in_grid' => true,
                'is_filterable_in_grid' => true,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable',
            ]
        );
    }

Replace you variable name with the self::PRESALE_START and self::PRESALE_END

after that run

bin/magento setup:upgrade

to create an attribute then now you can modify the product edit page to display this newly created attribute as a daterange.

create [vendor_name]/[module_name]/etc/adminhtml/di.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="MagentoCatalogUiDataProviderProductFormModifierPool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="presell-design-update" xsi:type="array">
                    <item name="class" xsi:type="string">[vendor_name][module_name]UiDataProviderProductFormModifierPreSellDesignUpdate</item>
                    <item name="sortOrder" xsi:type="number">120</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Now create a new file [vendor_name]/[module_name]/Ui/DataProvider/Product/Form/Modifier/PreSellDesignUpdate.php

add below code into modifier file.

<?php
namespace [vendor_name][module_name]UiDataProviderProductFormModifier;

use MagentoFrameworkStdlibArrayManager;
use MagentoCatalogUiDataProviderProductFormModifierAbstractModifier;

/**
 * Class ScheduleDesignUpdateMetaProvider customizes Schedule Design Update panel
 *
 * @api
 * @since 101.0.0
 */
class PreSellDesignUpdate extends AbstractModifier
{
    /**#@+
     * Field names
     */
    const PRESALE_START = 'presell_start';
    const PRESALE_END = 'presell_end';
    /**#@-*/

    /**
     * @var ArrayManager
     * @since 101.0.0
     */
    protected $arrayManager;

    /**
     * @param ArrayManager $arrayManager
     */
    public function __construct(ArrayManager $arrayManager)
    {
        $this->arrayManager = $arrayManager;
    }

    /**
     * @inheritdoc
     *
     * @since 101.0.0
     */
    public function modifyMeta(array $meta)
    {
        return $this->customizeDateRangeField($meta);
    }

    /**
     * @inheritdoc
     *
     * @since 101.0.0
     */
    public function modifyData(array $data)
    {
        return $data;
    }

    /**
     * Customize date range field if from and to fields belong to one group
     *
     * @param array $meta
     * @return array
     * @since 101.0.0
     */
    protected function customizeDateRangeField(array $meta)
    {
        if ($this->getGroupCodeByField($meta, self::PRESALE_START)
            !== $this->getGroupCodeByField($meta, self::PRESALE_END)
        ) {
            return $meta;
        }

        $fromFieldPath = $this->arrayManager->findPath(self::PRESALE_START, $meta, null, 'children');
        $toFieldPath = $this->arrayManager->findPath(self::PRESALE_END, $meta, null, 'children');
        $fromContainerPath = $this->arrayManager->slicePath($fromFieldPath, 0, -2);
        $toContainerPath = $this->arrayManager->slicePath($toFieldPath, 0, -2);

        $meta = $this->arrayManager->merge(
            $fromFieldPath . self::META_CONFIG_PATH,
            $meta,
            [
                'label' => __('Presell Product From'),
                'additionalClasses' => 'admin__field-date',
            ]
        );
        $meta = $this->arrayManager->merge(
            $toFieldPath . self::META_CONFIG_PATH,
            $meta,
            [
                'label' => __('To'),
                'scopeLabel' => null,
                'additionalClasses' => 'admin__field-date',
            ]
        );
        $meta = $this->arrayManager->merge(
            $fromContainerPath . self::META_CONFIG_PATH,
            $meta,
            [
                'label' => false,
                'required' => false,
                'additionalClasses' => 'admin__control-grouped-date',
                'breakLine' => false,
                'component' => 'Magento_Ui/js/form/components/group',
            ]
        );
        $meta = $this->arrayManager->set(
            $fromContainerPath . '/children/' . self::PRESALE_END,
            $meta,
            $this->arrayManager->get($toFieldPath, $meta)
        );

        return $this->arrayManager->remove($toContainerPath, $meta);
    }
}

now replace the PRESALE_START and PRESALE_END value with your create attribute_code

modifyMeta method is responsible for the UI related design modifyData method is responsible for the value of the attributes you can customize further as per your requirement.

Answered by Viral Langhanoja on January 8, 2021

For this, you need to create 2 attributes.

  1. Set Product as New From
  2. Set Product as New To

You have to set the input type as Date for each attributes and then you need to assign to the required set. Once it is done, then you can have your requirement.

Always it is better to refer dev docs of magento for fulfilling our requirement. http://docs.magento.com/m2/ee/user_guide/stores/attributes-input-types.html

Answered by Pavan Kumar on January 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP