0

I have this Command .php file inside Test/Coba/Command/SetCron.php

<?php
namespace Icube\Coba\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Test\Coba\Controller\Index\Index;
use Test\Coba\Controller\Index\Save;

class SaveCron extends Command
{
    protected $deleteItem;
    protected $saveItem;
    protected $helper;

    public function __construct(
        Index $deleteItem,
        Save $saveItem,
        \Test\Coba\Helper\Data $helper
    ){
        $this->deleteItem = $deleteItem;
        $this->saveItem = $saveItem;
        $this->helper = $helper;
        parent::__construct();
    }
    
    protected function configure()
    {
        $this->setName('save:category');
        $this->setDescription('Demo command line');
        
        parent::configure();
    }

    protected function execute(InputInterface $input,OutputInterface $output){
        $this->deleteItem->execute();
        $this->saveItem->execute();
        $output->writeln("Hello World Theree!");
    }
}

and my crontab.xml inside Test/etc/crontab.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">   
    <type name="Magento\Framework\Console\CommandList">
            <arguments>
                <argument name="commands" xsi:type="array">
                    <item name="autocategory_cli" xsi:type="object">Test\Coba\Console\SaveCron</item>
                </argument>
            </arguments>
    </type>
</config>

i did set:di:compile and cache:flush but unfortunately my CLI wont registered in the system and give this error message, anyone know what mistakes that i did?

enter image description here

edit:

Index.php <?php

namespace Test\Coba\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use \Magento\Catalog\Model\CategoryLinkRepository;
use \Magento\Catalog\Api\CategoryLinkManagementInterface;

class Index extends Action
{
    protected $_pageFactory;
    protected $productCollectionFactory;
    protected $_categoryLinkManagement;
    protected $_categoryLinkRepository;

    public function __construct(
        Context $context,
        PageFactory $pageFactory,
        CollectionFactory $collectionFactory,      
        CategoryLinkRepository $_categoryLinkRepository,
        CategoryLinkManagementInterface $_categoryLinkManagement
    ) {
        $this->_pageFactory = $pageFactory;
        $this->productCollectionFactory = $collectionFactory;
        $this->_categoryLinkRepository = $_categoryLinkRepository;
        $this->_categoryLinkManagement = $_categoryLinkManagement;
        return parent::__construct($context);
    }

    private function DeleteProductFromCategory()
    {
        $categoryId = 41;
        $productCollection = $this->productCollectionFactory->create()
        ->addCategoriesFilter(['in' => $categoryId]);

        foreach ($productCollection as $product){
            $this->_categoryLinkRepository->deleteByIds($categoryId, $product->getSku());
            echo $product->getSku() . "has been deleted";
        }
    }

    public function execute() 
    {
        $this->DeleteProductFromCategory();
    }
}

Save.php

<?php

namespace Test\Coba\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Store\Model\ScopeInterface;
use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use \Magento\Catalog\Api\CategoryLinkManagementInterface;

class Save extends Action
{
    protected $_pageFactory;
    protected $_scopeConfig;
    protected $productCollectionFactory;
    protected $_categoryLinkManagement;

    public function __construct(
        Context $context,
        PageFactory $pageFactory,
        ScopeConfigInterface $scopeConfig,
        CollectionFactory $collectionFactory,
        CategoryLinkManagementInterface $_categoryLinkManagement
    ) {
        $this->_pageFactory = $pageFactory;
        $this->_scopeConfig = $scopeConfig;
        $this->productCollectionFactory = $collectionFactory;
        $this->_categoryLinkManagement = $_categoryLinkManagement;
        return parent::__construct($context);
    }
    
    private function CreatedAt()
    {
        $date = $this->_scopeConfig->getValue('category_setting/general/day',ScopeInterface::SCOPE_STORE);
        $month = $this->_scopeConfig->getValue('category_setting/general/month',ScopeInterface::SCOPE_STORE);
        $year = $this->_scopeConfig->getValue('category_setting/general/year',ScopeInterface::SCOPE_STORE);
        return  $year .'-' .$month .'-' .$date . ' 00:00:00';
    }

    private function AddNewProductToCategory()
    {
        $categoryId = array('41');
        $productCollection = $this->productCollectionFactory->create()
        ->addAttributeToSelect('*')
        ->addFieldToFilter('created_at', ['gteq' =>$this->CreatedAt()]);

        foreach ($productCollection as $product){ 
            if($product->getData('Exclude_From_New') == 0) {
                $this->_categoryLinkManagement->assignProductToCategories($product->getSku(), $categoryId);
                echo $product->getName(). 'added';
            }
        }
    }

    public function execute() 
    {
        $this->AddNewProductToCategory();
    }
}
2
  • 1
    I think configuration must be defined inside the di.xml not in crontab Sep 20 at 9:03
  • i moved the config to my di.xml, but after i setup:upgrade, new errors occured Area code is not set. do you know what this errors refers to? Thanks in advance @SiarheyUchukhlebau
    – Wavesolid
    Sep 20 at 9:19
0

Please add this in your frontend/di.xml or adminhtml/di.xml based on the use case

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Icube\Coba\Console\SaveCron">
      <arguments>
         <!-- configure the command name via constructor $name argument -->
         <argument name="name" xsi:type="string">save:category</argument>
      </arguments>
   </type>
</config>

Then update the di.xml with commandListInterface

Please follow this Magento doc for the right way to create cli commands https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cli-cmds/cli-howto.html

if the state is required please update your code like this there are many states in Magento: admin adminhtml catalog crontab doc frontend global setup

/** @var \Magento\Framework\App\State **/
private $state;

public function __construct(\Magento\Framework\App\State $state) {
    $this->state = $state;
    parent::__construct();
}

public function execute() {
    $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND); // or \Magento\Framework\App\Area::AREA_ADMINHTML, depending on your needs
}

Note: Crontab.xml magento guide https://devdocs.magento.com/guides/v2.4/config-guide/cron/custom-cron-tut.html

5
  • i already moved to di.xml but right now an error Area code is not set occured.
    – Wavesolid
    Sep 20 at 9:50
  • use Test\Coba\Controller\Index\Index; use Test\Coba\Controller\Index\Save; I need to see the above two files There might be a code that requires area code to be set I hope there is some frontend context been used That is why it requires area code Sep 20 at 10:01
  • Just remove Index and Save classes in Import, Constructor, then the command will work you need to write the code inside this execute method instead using Controller Sep 20 at 10:02
  • i already updated my thread with my codes, please kindly to check.
    – Wavesolid
    Sep 20 at 10:15
  • yes, you updated the namespace did you tried by removing those two controllers? Sep 20 at 10:20

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.