0

below is the cron job code that suppose to delete customer if they have value of 1 in deleteOrders field but it not doing that, what am i missing?

<?php

namespace Vendor\ThreeYearOrders\Cron;

use Magento\Customer\Model\Session;

class DeleteOrder
{
    /**
     * @var Session
     */
    protected $_customerSession;
    
    /**
     * @param Session $customerSession
     */
    public function __construct(Session $customerSession)
    {
        $this->_customerSession = $customerSession;
    }

    public function execute()
    {
        $customerId = $this->_customerSession->getCustomerId();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
        $log = $objectManager->get('\Psr\Log\LoggerInterface');

        $connection = $resource->getConnection();
        $tableName = $connection->getTableName('customer_entity');

        try {
            $where = [
                'entity_id = ?' => $customerId,
                'deleteOrders = ?' => 1
            ];
            $connection->delete($tableName, $where);
            $log->info('Customer is deleted');
        } catch (\Exception $e) {
            $log->error("Error deleting customer: " . $e->getMessage());
        }
    }
}

This is crontab.xml file below that execute and run cronjob file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="Vendor_threeyearorders_delete_orders" instance="Vendor\ThreeYearOrders\Cron\DeleteOrder" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Setup file

<?php

namespace Vendor\ThreeYearOrders\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        $table = $installer->getTable('customer_entity');

        $installer->getConnection()->addColumn(
            $table,
            'deleteOrders',
            [
                'type' => Table::TYPE_INTEGER,
                'nullable' => true,
                'default' => null,
                'comment' => 'Delete Orders'
            ]
        );

        $installer->endSetup();
    }
}
4

2 Answers 2

2

Try all steps it will be useful for you

1.Create the registration file on path app/code/Vendor/ThreeYearOrders/registration.php

 <?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_ThreeYearOrders',
    __DIR__
);

2.Define the module's module.xml file on path app/code/Vendor/ThreeYearOrders/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_ThreeYearOrders" setup_version="1.0.0" />
</config>

3.Create the cron job class at app/code/Vendor/ThreeYearOrders/Cron/DeleteOrder.php

<?php

namespace Vendor\ThreeYearOrders\Cron;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Psr\Log\LoggerInterface;

class DeleteOrder
{
    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @param CustomerRepositoryInterface $customerRepository
     * @param LoggerInterface $logger
     */
    public function __construct(
        CustomerRepositoryInterface $customerRepository,
        LoggerInterface $logger
    ) {
        $this->customerRepository = $customerRepository;
        $this->logger = $logger;
    }

    public function execute()
    {
        try {
            $customersToDelete = $this->customerRepository->getList(
                $this->customerRepository->getSearchCriteria()
                    ->addFilter('deleteOrders', 1)
            );

            foreach ($customersToDelete->getItems() as $customer) {
                $this->customerRepository->delete($customer);
                $this->logger->info('Customer with ID ' . $customer->getId() . ' has been deleted.');
            }
        } catch (\Exception $e) {
            $this->logger->error("Error deleting customers: " . $e->getMessage());
        }
    }
}

4.Create the cron job configuration file at app/code/Vendor/ThreeYearOrders/etc/crontab.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="vendor_threeyearorders_delete_orders" instance="Vendor\ThreeYearOrders\Cron\DeleteOrder" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

5.Run the setup:upgrade command

bin/magento setup:upgrade

After creating the necessary files, run the following command from the Magento root directory to apply the database changes and register the module

0

Update your DeleteOrder.php with below code and run php bin/magento s:d:c

<?php

namespace Vendor\ThreeYearOrders\Cron;

use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\Registry;

class DeleteOrder
{
    /**
     * @var customerFactory
     */
    protected $customerFactory;

    /**
     * @var registry
     */
    protected $registry;
    
    /**
     * @param CustomerFactory $customerFactory
     * @param Registry $registry
     */
    public function __construct(
        CustomerFactory $customerFactory,
        Registry $registry
    ) {
        $this->customerFactory = $customerFactory;
        $this->registry = $registry;
    }

    public function execute()
    {
        $this->registry->register('isSecureArea', true);
        $customerCollection = $this->customerFactory->create()->getCollection()
                        ->addFieldToFilter("deleteOrders", 1)
                        ->load();

        if ($customerCollection && count($customerCollection) > 0) {
            foreach ($customerCollection as $customer) {
                    $id = $customer->getId();
                    $customer = $this->customerFactory->create()->load($id);
                    $customer->delete();
            }
        }
    }
}
2
  • Instead of $customerCollection you meant $collection? or it right like this?
    – Bayzel
    May 25 at 6:56
  • @Bayzel yup right, I have updated it. Please let me know if you face any issue May 25 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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