4

I have tried to create datetime attribute in Magento 2. Below is my script:

 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

 $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'course_start_datetime');
 $eavSetup->addAttribute(
       \Magento\Catalog\Model\Product::ENTITY,
        'course_start',
        [
            'group' => 'Custom Attribute',
            'label' => 'Enable Start Date',
            'type' => 'datetime',
            'input' => 'date',
            'input_renderer' => 'Velanapps\Test\Block\Adminhtml\Form\Element\Datetime',
            'class' => 'validate-date',
            'backend' => 'Magento\Catalog\Model\Attribute\Backend\Startdate',
            'required' => false,
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
            'visible' => true,
            'required' => false,
            'user_defined' => true,
            'default' => '',
            'searchable' => true,
            'filterable' => true,
            'filterable_in_search' => true,
            'visible_in_advanced_search' => true,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false
        ]
    );

And the block for input renderer is below:

  <?php
  namespace Velanapps\Test\Block\Adminhtml\Form\Element;
  use Magento\Framework\Data\Form\Element\Date;

  class DateTime extends Date {
       public function getElementHtml() {
           $this->setDateFormat($this->localeDate->getDateFormat(\IntlDateFormatter::SHORT));
           $this->setTimeFormat($this->localeDate->getTimeFormat(\IntlDateFormatter::SHORT));
           return parent::getElementHtml();
       }
  }

But is only show date. Please let me know if anybody has created with time already.. Thanks in advance...

  • Have you got answer? – Naveenbos Sep 18 '17 at 11:09
8

One of the possible solutions is to use Modifiers.

First create Velanapps\Test\etc\adminhtml\di.xml:

<?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="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool">
        <arguments>
            <argument name="modifiers" xsi:type="array">
                <item name="course_start" xsi:type="array">
                    <item name="class" xsi:type="string">Velanapps\Test\Ui\DataProvider\Product\Form\Modifier\Datetime</item>
                    <item name="sortOrder" xsi:type="number">100</item>
                </item>
            </argument>
        </arguments>
    </virtualType>
</config>

Then add Modifier Velanapps\Test\Ui\DataProvider\Product\Form\Modifier\Datetime.php:

<?php
namespace Velanapps\Test\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;
use Magento\Framework\Stdlib\ArrayManager;

/**
 * Data provider for "Custom Attribute" field of product page
 */
class Datetime extends AbstractModifier
{
    /**
     * @param ArrayManager                $arrayManager
     */
    public function __construct(
        ArrayManager $arrayManager
    ) {
        $this->arrayManager = $arrayManager;
    }

    /**
     * {@inheritdoc}
     */
    public function modifyMeta(array $meta)
    {
        $meta = $this->enableTime($meta);

        return $meta;
    }

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

    /**
     * Customise Custom Attribute field
     *
     * @param array $meta
     *
     * @return array
     */
    protected function enableTime(array $meta)
    {
        $fieldCode = 'course_start';

        $elementPath = $this->arrayManager->findPath($fieldCode, $meta, null, 'children');
        $containerPath = $this->arrayManager->findPath(static::CONTAINER_PREFIX . $fieldCode, $meta, null, 'children');

        if (!$elementPath) {
            return $meta;
        }

        $meta = $this->arrayManager->merge(
            $containerPath,
            $meta,
            [
                'children'  => [
                    $fieldCode => [
                        'arguments' => [
                            'data' => [
                                'config' => [
                                    'default' => '',
                                    'options'       => [
                                        'dateFormat' > 'Y-m-d',
                                        'timeFormat' => 'HH:mm:ss',
                                        'showsTime' => true
                                    ]
                                ],
                            ],
                        ],
                    ]
                ]
            ]
        );


        return $meta;
    }
}

Clear cache and your attribute should now show time as well. I also suggest to remove input_renderer from attribute creation script. Most likely you don't need backend either.

  • It's not working. I have added attribute from magento admin then in custom module add this code. But i am getting blank page in admin and front side also. – Magecode Oct 25 '17 at 13:42
  • Please accept this answer. This is the right answer. To add DateTime picker for Products, this is the right way. Well done ! – Ahsan Horani Jun 28 at 7:41
0

Please try below code :

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * Install attributes
 */
class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
    /**
     * @var \Magento\Catalog\Setup\CategorySetupFactory
     */
    protected $categorySetupFactory;

    /**
     * Init
     *
     * @param \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory
     */
    public function __construct(
        \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory
    ) {
        $this->categorySetupFactory = $categorySetupFactory;
    }
     public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {

        $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);

        $setup->startSetup();

        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'course_start',
            [
                'type' => 'datetime',
                'backend' => '',
                'frontend' => 'Magento\Eav\Model\Entity\Attribute\Frontend\Datetime',
                'label' => 'Enable Start Date',
                'input' => 'date',
                'class' => '',
                'source' => '',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => true,
                'user_defined' => false,
                'default' => '',
                'sort_order' => 9,
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => ''
            ]
        ); 

         $setup->endSetup();
    }
}   

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