Question

I am brand new to Magento module development, and I need some help getting started. My goal is relatively simple: I'd like to create a module which fetches all products with a custom attribute 'amazon_ready' set to true, saves these out to a file, and then sets that attribute for all those products back to false. I'd like this to happen every 24 hours.

So far, I have set up a simple cron module using the example found here.

<?php
namespace SuttersMill\AmazonCron\Cron;
use \Psr\Log\LoggerInterface;

class Test {
    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
       * Write to system.log
       *
       * @return void
       */
    public function execute()
    {
        $this->logger->info('Cron Works');
        // Code to pull in product entities from datastore.
    }
}

How do I get all products where the custom attribute is set to true? Any pointers in the right direction would be immensely helpful.

Was it helpful?

Solution

You will have to fetch a product collection and filter it based on your custom attribute. You can also fetch most (but not all) of attributes from filter collection items.

Try following code ;

<?php
namespace SuttersMill\AmazonCron\Cron;
use \Psr\Log\LoggerInterface;

class Test {
    protected $logger;
    protected $collectionFactory;
    public function __construct(LoggerInterface $logger,\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory)
    {
        $this->logger = $logger;
        $this->collectionFactory = $collectionFactory;
    }

    /**
       * Write to system.log
       *
       * @return void
       */
    public function execute()
    {
        $this->logger->info('Cron Works');
        // Code to pull in product entities from datastore.
        $productCollection = $this->collectionFactory->create();
        /** Apply filters here */
        $filteredProducts = $productCollection->addAttributeToSelect('*')->addAttributeToFilter('attribute_code',attribute_value);
         foreach($filteredProducts as $product){
            $this->logger->info('  ' .$product->getName() . '  ' );
          }
    }
}

Above should print name of the products you want in your logs after you replace attribute_code to the attribute code of your custom attribute and attribute_value to required value (true in your case ).

Feel free to ask any queries if required.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top