0

I'm trying to adapt some scripts I created (fully functional but not very Magento2) into modules but after many hours of reading, still don't really understand how it works. For exemple, this scripts called "delete.php" retrieve all configurable/simple associated which are out of stock, convert and download in a csv so I can use the import process (behavior delete) to remove all old products.

<?php

ini_set('memory_limit', -1);
ini_set('max_execution_time', 0);
error_reporting(E_ALL);
ini_set('display_errors', '1');

use Magento\Framework\App\Bootstrap;
include('../../app/bootstrap.php');

$params =  $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection
            ->addAttributeToSelect('*')
            ->setPageSize(500) //Selecting 500 products for TEST
            ->load();
echo "sku" . ';' . "name" . ';' . "mgs_brand" . ';' . "urbmag_season" . "\n";
foreach($collection as $product){

    $productType = $product->getTypeId(); // look if CONFIGURABLE

    if ($productType == "configurable" AND !$product->isAvailable()) { // CONF + OUT OF STOCK
    $productSku = $product->getSku();
    $productName = $product->getName();
    $productBrand = $product->getAttributeText('mgs_brand'); //brand attribute for filter in csv
    $productSeason = $product->getAttributeText('urbmag_season'); // season attribute for filter in csv 
        echo $productSku.';'.$productName.';'.$productBrand.';'.$productSeason."\n";

        $children = $product->getTypeInstance()->getUsedProducts($product); // simple associated
        foreach ($children as $child) {
      $childSku = $child->getSku();
      $childName = $child->getName();
            echo $childSku.';'.$childName.';'.$productBrand.';'.$productSeason."\n";
        }
    }
}

chdir('convert_csv');
if( file_exists ('delete.csv'))
     unlink('delete.csv') ;

//*****************  DOWNLOAD CSV        ***********************
$fp = fopen('delete.csv', 'w+');
fclose($fp);

header("Content-type: text/csv");
header("Content-disposition: attachment; filename = delete.csv");
readfile("delete.csv");

I follow all the tutorials I found, like How to create a basic module in Magento 2 but I can't adapt this for my needs. Idea here is to call an url that execute my function. Would someone have the kindness and patience to explain to me step by step how to make my module ?

1

Follow below steps to create module:

Create registration.php file at app/code/Test/Delete/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Test_Delete',
    __DIR__
);

Create module.xml file at app/code/Test/Delete/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Test_Delete" setup_version="1.0.0"></module>
</config>

create routes.xml file at app/code/Test/Delete/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="delete" frontName="delete">
            <module name="Test_Delete" />
        </route>
    </router>
</config>

Create block file at app/code/Test/Delete/Block/Index/Index.php

<?php

namespace Test\Delete\Block\Index;


class Index extends \Magento\Framework\View\Element\Template {

    $_collectionFactory;

    public function __construct(
    \Magento\Catalog\Block\Product\Context $context, 
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
    array $data = []
    ) {
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context, $data);

    }

    public function getProductCollection(){
        return $this->_collectionFactory->create();
    }

}

create Template delete.phtml file at app/code/Test/Delete/view/frontend/templates/delete.phtml

<?php

/** $block refers to Test\Delete\Block\Index\Index **/

$productCollection = $block->getProductCollection();
$collection = $productCollection
            ->addAttributeToSelect('*')
            ->setPageSize(500) //Selecting 500 products for TEST
            ->load();
echo "sku" . ';' . "name" . ';' . "mgs_brand" . ';' . "urbmag_season" . "\n";
foreach($collection as $product){

    $productType = $product->getTypeId(); // look if CONFIGURABLE

    if ($productType == "configurable" AND !$product->isAvailable()) { // CONF + OUT OF STOCK
    $productSku = $product->getSku();
    $productName = $product->getName();
    $productBrand = $product->getAttributeText('mgs_brand'); //brand attribute for filter in csv
    $productSeason = $product->getAttributeText('urbmag_season'); // season attribute for filter in csv 
        echo $productSku.';'.$productName.';'.$productBrand.';'.$productSeason."\n";

        $children = $product->getTypeInstance()->getUsedProducts($product); // simple associated
        foreach ($children as $child) {
      $childSku = $child->getSku();
      $childName = $child->getName();
            echo $childSku.';'.$childName.';'.$productBrand.';'.$productSeason."\n";
        }
    }
}

//change file path if delete.csv in root then use BP.'delete.csv'

chdir('convert_csv');
if( file_exists ('delete.csv'))
     unlink('delete.csv') ;

//*****************  DOWNLOAD CSV        ***********************
$fp = fopen('delete.csv', 'w+');
fclose($fp);

header("Content-type: text/csv");
header("Content-disposition: attachment; filename = delete.csv");
readfile("delete.csv");

create layout file at app/code/Test/Delete/view/frontend/layout/delete_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">

    <head>
        <title>Delete</title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Test\Delete\Block\Index\Index" name="delete_index_index" template="Test_Delete::delete.phtml"/>
        </referenceContainer>
    </body>
</page>

Add below Index.php controller file at app/code/Test/Delete/Controller/Index/Index.php

<?php
namespace Test\Delete\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        return $this->_pageFactory->create();
    }
}

After creating module run below command:

  • php bin/magento setup:upgrade
  • php bin/magento cache:flush

Browse URL your-store-url/delete/index/index

7
  • thanks for your help! I created my module as explain above, run commands to enable it, check by module:status command so far so good. But when I browse url => error 404. any idea ? Mar 18 '18 at 23:00
  • Updated code of delete_index_index.xml please update this code flush cache browse same url Mar 19 '18 at 5:16
  • sorry for being too noobs but I updated the delete_index_index.xml as explain, flush cache even reindex and still error 404 when accessing url... I think I will keep using my scripts in the pub/scripts folder or is it too dangerous using the objectManager like that ? Mar 19 '18 at 19:41
  • @urbansurfers sorry i forgot to add controller file please add controller file and flush cache your issue will be resolved i hope Mar 21 '18 at 15:11
  • 1
    @urbansurfers I have updated block please update it and check again it will work Mar 22 '18 at 15:32

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.