3

My specific use case is that I want to set the news_from_date and news_to_date for the a thirty day period from when the product is created. I would like this to work so when a user goes into the admin area to create the product this field will automatically be filled out with these values, and they can remove them if they would like.

I've looked at this post (Set default value to news_from_date and news_to_date) and this one (Get product from save event observer - Magento 2) which has helped me get it to set the default value before it is saved, but it doesn't help automatically fill in the values in the admin UI.

I created a module that does exactly what I want in Magento 1, but I can not get the same thing working in Magento 2.

Here is the code I am using:

/etc/adminhtml/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_new_action">
        <observer name="new_product_observer" instance="CrazyDog\NewProducts\Observer\Product" />
    </event>
</config>

/observer/Product.php

class Product implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $new_from_date = date('Y-m-d'); // --- Today
        $product->setNewsFromDate($new_from_date);
        $new_to_date = date('Y-m-d', strtotime('+30 days')); // --- 30 days from now
        $product->setNewsToDate($new_to_date);

        // --- These print in the admin area with correct values, so I know the observer is running
        echo $product->getNewsFromDate();
        echo $product->getNewsToDate();
    }
}

I can not figure out why these values aren't populating into the fields. I've tried with other attributes like the name as well, and they will print when trying to debug, but they do not populate into the fields. I'm not sure if this is an issue related to how javascript is now being used in the back end for a lot of this stuff.

Any insights would be helpful, thanks! :)

0

I think your date format is wrong you should try

$new_from_date = date('m/d/Y'); // --- Today
  • Changing the format did not get it working as I wanted. Like I said, I've tried with other attributes as well such as 'name' but none of them are populating into the fields. – BVBAccelerate Nov 17 '16 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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