magento2 – Activation/Deactivation and uninstallation module hook magento 2

I am writing an extension for Magento 2. When my extension/module is activated. I want to send a request to my backend to register a merchant. And when the merchant deletes my extension, I also send a DELETE request to my backend.

How can I listen to the Magento activation/deactivation and uninstallation event? (In WordPress we have those hooks)

What package do we use for HTTP request in magento2?

Thank you very much!

Magento2 Impact of Setup:upgrade – Magento Stack Exchange

I am preparing for certification and I came across one of the questions and I wanted to confirm the options. I know option 4 is correct for sure, confused between 1 and 2. I know setup:upgrade does not clear Magento cache. any help will be appreciated

Question
You have to install a new module on the production environment. All the module is adding a new product attribute. You enabled maintenance mode, copied the module code, run bin/magento setup: upgrade and
disabled maintenance mode.

What two risks does this process pose? (Choose two.)

  1. It will clean all caches which will cause performance degradation
  2. The new attribute will be invisible on the storefront until the cache is cleaned manually
  3. It will void all active sessions
  4. It will clean static assets from the pub/static folder

magento2 – Magento 2: Custom added ajax pagination not working

I have added ajax pagination in custom module collection. I have total 50 item in collection and added limit is 5 show total page is 10.

There is showing only 5 page and not showing next page and also not active clickable page and Next arrow also not working.

When I click on 5 number page or Next arrow then there should be display next page like 6 7 8 etc. But it is not showing.

I have follow the below File path to implement pagination.

Step 1: Block file code.

File path: app/code/Vendor/Module/Block/Test.php

public function getPagerHtml()
{
    if ($this->getLayout()->getBlock('test.page.pager')) {
        $this->pager = $this->getLayout()->getBlock('test.page.pager');

        return $this->pager->toHtml();
    }
    if (!$this->pager) {
        $this->pager = $this->getLayout()->createBlock(
            Pager::class,
            'test.page.pager'
        );

        if ($this->pager) {
            $this->pager->setUseContainer(
                false
            )->setShowPerPage(
                false
            )->setShowAmounts(
                false
            )->setFrameLength(
                $this->_scopeConfig->getValue(
                    'design/pagination/pagination_frame',
                    MagentoStoreModelScopeInterface::SCOPE_STORE
                )
            )->setJump(
                $this->_scopeConfig->getValue(
                    'design/pagination/pagination_frame_skip',
                    MagentoStoreModelScopeInterface::SCOPE_STORE
                )
            )->setLimit(5)->setCollection(
                $this->getLocationCollection()
            );

            return $this->pager->toHtml();
        }
    }

    return '';
}

public function getLocationCollection()
{
    $pageNumber = (int)$this->getRequest()->getParam('p') ? (int)$this->getRequest()->getParam('p') : 1;
    if (!$this->itemCollection) {
        $this->itemCollection = $this->itemCollectionFactory->create();
    }
    $this->itemCollection->setCurPage($pageNumber);
    $this->itemCollection->setPageSize(5);

    return $this->itemCollection;
}

protected function _prepareLayout()
{       
      
    $this->getPagerHtml();

    if ($this->pager && !$this->pager->isFirstPage()) {
        $this->addPrevNext(
            $this->getUrl('testpage/index/ajax', ('p' => $this->pager->getCurrentPage() - 1)),
            ('rel' => 'prev')
        );
    }
    if ($this->pager && $this->pager->getCurrentPage() < $this->pager->getLastPageNum()) {
        $this->addPrevNext(
            $this->getUrl('testpage/index/ajax', ('p' => $this->pager->getCurrentPage() + 1)),
            ('rel' => 'next')
        );
    }


    return parent::_prepareLayout();
}

 /**
 * Add prev/next pages
 *
 * @param string $url
 * @param array $attributes
 *
 */
private function addPrevNext($url, $attributes)
{
    $this->pageConfig->addRemotePageAsset(
        $url,
        'link_rel',
        ('attributes' => $attributes)
    );
}

Step 2: Controller file.

File path: app/code/Vendor/Module/Controller/Index/Ajax.php

public function execute()
{
    $params = $this->getRequest()->getParams();
    $storeId = $this->storeManager->getStore()->getId();

    if(isset($params('pageNo'))){
        $pageNo = $params('pageNo');
    }else{
        $pageNo = 1;
    }

    $collection = $this->collectionFactory->create()
                ->addFieldToFilter('is_active', 1)
                ->addStoreFilter($storeId)
                ->setPageSize(5) 
                ->setCurPage($pageNo); 

    $data = $this->prepareData($collection->getData());
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($data);
    return $resultJson;
}

Step 3: Template file.

File path:
app/code/Vendor/Module/view/frontend/templates/pagetest.phtml

<?php  if ($pager = $block->getPagerHtml()): ?>
    <div class="testpage-pager-container"><?= /** @escapeNotVerified */ $pager; ?></div>
<?php endif;  ?>

Step 4: JS file code.

File path: app/code/Vendor/Module/view/frontend/web/js/testpage.js

$(".testpage-pager-container li a").live('click', function(event) {
    event.preventDefault();

    var pagignationUrl= $(this).attr('href'); 
    var pageSplit = pagignationUrl.split('/');
    var pageNo = pageSplit(pageSplit.length - 2);  
    $.ajax({
        url : self.options.ajaxUrl,
        type: self.options.method,
        dataType: 'json',
        data: {pageNo: pageNo},
        showLoader: true,
        beforeSend: function() {
        },
        success : function(res) {  
           $('#store-list').html(res);
        },
        error : function(request,error)
        {
            alert("Error");
        }
    });

});

enter image description here

Any help would be appropriated. Thanks.

magento2 – Add Custom Data to Rest Api response

I tried to add custom data to the endpoint V1/categories but ended up with getting error

My code is below

  1. etc/extension_attributes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="MagentoCatalogApiCategoryRepositoryInterface">
        <attribute code="banner_slider" type="string" />
    </extension_attributes>
</config>

2.di.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="MagentoCatalogApiCategoryRepositoryInterface">
        <plugin name="banner_image_data" type="VendorModuleNamePluginModelCategoryRepository"/>
    </type>
</config>

3.Plugin

use MagentoCatalogModelCategoryRepository as Subject;

class CategoryRepository
{

    /**
     * @param Subject $subject
     * @param CategoryInterface $data
     * @return CategoryInterface
     */
    public function afterGet(
        Subject $subject,
        CategoryInterface $data
    )
    {
        $extensionAttributes = $data->getExtensionAttributes();
        $extensionAttributes->setBannerSlider('sandesh');
        $data->setExtensionAttributes($extensionAttributes);
        return $data;
    }
}

My error

 Call to undefined method MagentoCatalogApiDataCategoryExtension::setBannerSlider()

magento2 – Magento 2 how to override MagentoCheckoutModelCart.php file

You can override using preference method in di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagentoCheckoutModelCart" type="VendorModuleNameModelCart" />
</config>

You have to create Cart class in your module in order to extend MagentoCheckoutModelCart. E.g:

<?php
namespace VendorModuleNameModel;


class Cart extends MagentoCheckoutModelCart
{
     //override respective methods
}

magento2 – Magento 2.3.x Admin Panel keeps loading

I have installed Magento 2.3.5-p1 and also tried 2.3.4-p2 on Centos 7, with Nginx & PHP-FPM, maria DB with following commands.

1. /var/www/magento < owner by MAGENTO:NGINX user (I have created a pool for magento:nginx)
2. find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
3. find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
4. chmod u+x bin/magento
6. su magento

7.  bin/magento setup:install --base-url='https://www.example.com/' 
--base-url-secure='https://www.example.com/' 
--backend-frontname='' 
--db-host='localhost' --db-name='' --db-user='' 
--db-password='' --admin-firstname='example' 
--admin-lastname='Admin' --admin-email='' 
--admin-user='admin' --admin-password='' --language='en_US' 
--currency='USD' --timezone='UTC' --use-rewrites=1 --use-secure-admin=1 --use-secure=1

Once completed, my FRONTEND (home page) works absolutely fine, i just have 2 errors in the javascript console log:

(Error) Failed to load resource: the server responded with a status of 404 () (requirejs-config.js, line 0)
(Error) Refused to execute https://www.example.com/pub/static/version1594092941/frontend/Magento/luma/en_US/requirejs-config.js as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type.

But when I open admin panel, I can login into it. However, after logging in it keeps loading. I have tried several methods available online such as:

1. rm -rf pub/static/* (except .htaccess) refresh page
2.  
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:di:compile
3.
vi app/etc/di.xml <-- Change Symlink to Copy
rm -rf pub/static/*
refresh page
4. 
rm -rf var/*
bin/magento setup:static-content:deploy -f
bin/magento c:c
5. bin/magento cache:enable

I have tried to install it under both php-fpm and nginx group, also as nginx:nginx. Nothing works, admin panel just keeps loading.

What am I missing here?

The errors i get on admin panel JS console logs

enter image description here

magento2 – magento1 migrate to multiple magento 2 stores

Anyone knows what happen for all the migrate changes tables in m1, if I want to start migration to a new m2 store.

E.g. I migrated m1 data to the first m2 store and all the deltalog tables (with prefix m2_cl_*) and triggers (for tracking changes) have been created in the M1. Now I want m1 data to migrate to an another m2 store. What will happen will all the deltalog tables and triggers. Will they be dropped and recreated? I use Magento data migration tool.

magento2: add product then save error

the error code is :
Class MagentoDownloadableApiDataSampleInterfaceFactory does not exist

I add the product, when I submit and save the product. I test it for many days, it still this error, does I configure it wrong?

the Class of the SampleInterface Factory does not exist?
who can give me the code on how to solve this error?

magento2 – How to delete specific product images from Magento 2 database and physical images from folder?

Deleting selected product / SKU images from Magento 2 database and the physical images files from the media product catalog folders which are dynamically created by Magento during image upload.

  1. Locate the image and image physical path. In the database, the images and the physical path reference of the images are stores in the below 3 tables
  • catalog_product_entity_media_gallery
    //This is where the physical
    image path is stored
  • catalog_product_entity_media_gallery_value
    //This table has the storeid, valueid, product entity id and the
    position of the images
  • catalog_product_entity_media_gallery_value_to_entity //This table is
    where the mapping between the product entity id and valueid mapping
    done.
  • And the images are stored physically under magento2rootpath/pub/media/catalog/product/x/x/x
  1. First step is to identify the physical path of the server and delete from the media –> catalog –> product path, I used the below query to create a file with remove command and the image physical path on the server.

This example was executed on Ubuntu 16.04, the below commands and sql querie. Will run on any Linux distro and Mysql.

Basically create a file with the below command to delete the images,

run the below query on the command prompt.

 - mysql -u username -p databasename -e "select concat('rm -f
   /home/magento2rootpath/pub/media/catalog/product',value) from
   catalog_product_entity_media_gallery  where value_id in (select
   value_id from catalog_product_entity_media_gallery_value_to_entity
   where entity_id in (select entity_id from catalog_product_entity
   where sku in ('SKU1','SKU2','SKU3'))) and attribute_id=90;" >
   imagefilestodelete.sh

In my case, Magento is installed in folder /home/magento2rootpath – replace with your actual magento root path and replace SKU1, SKU2, SKU3 with your actual product SKU

Output of the generated file imagefilestodelete.sh

rm -f /home/magento2rootpath/pub/media/catalog/product/4/m/4m6a6330.jpg
rm -f /home/magento2rootpath/pub/media/catalog/product/4/m/4m6a6332.jpg
rm -f /home/magento2rootpath/pub/media/catalog/product/4/m/4m6a6333.jpg
rm -f /home/magento2rootpath/pub/media/catalog/product/4/m/4m6a6335.jpg

From the CLI run the below command

sh imagefilestodelete.sh

Now that we have deleted the physical image files from the media catalog respective image path folder, we will now need to remove the same from database, I used the below sql queries in the same order to remove the file references from database.

  1. Remove the image references from the respective tables in Magento

Login to your mysql with user having privilege to execute delete
queries

 - delete from catalog_product_entity_media_gallery where value_id in
   (select value_id from catalog_product_entity_media_gallery_value_to_entity where entity_id
   in (select entity_id from catalog_product_entity where sku in
   ('SKU1','SKU2','SKU3'))) and attribute_id=90;

 - delete from catalog_product_entity_media_gallery_value_to_entity
   where entity_id in (select entity_id from catalog_product_entity
   where sku in ('SKU1','SKU2','SKU3'));

 - delete from catalog_product_entity_media_gallery_value where
   entity_id in (select entity_id from catalog_product_entity where sku
   in ('SKU1','SKU2','SKU3'));

NOTE: Before you execute the above delete queries, run SELECT to check the entries. To do that replace delete from above queries to SELECT *

This way it was easier for me to delete images for specific products on production and not truncate the entire tables.