Skip to content

Instantly share code, notes, and snippets.

@andrewdaluz
Last active April 13, 2022 14:24
Show Gist options
  • Save andrewdaluz/6c6f0350914dffebad2311057223b03e to your computer and use it in GitHub Desktop.
Save andrewdaluz/6c6f0350914dffebad2311057223b03e to your computer and use it in GitHub Desktop.

Redis keys commands

redis-cli -p 6370  KEYS * | xargs -n 1 redis-cli -p 6370 dump

Setup permissions

find . -type f -exec chmod 664 {} \;
find . -type d -exec chmod 775 {} \;
find var pub/static pub/media app/etc -type f -exec chmod g+w {} \;
find var pub/static pub/media app/etc -type d -exec chmod g+ws {} \;
chmod u+x bin/magento

Validate new theme configurations or deploy it

-

Using Grunt

https://devdocs.magento.com/guides/v2.2/frontend-dev-guide/css-topics/css_debug.html

Errors

There are no commands defined in the “cache” namespace

Solution 1:

The general main cause of this kind of error is missing etc/module.xml file in your module. Or, missing setup_version code in module.xml file.

Here is a sample module.xml file of a module named YourNamespace_YourModule.

app/code/YourNamespace/YourModule/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="YourNamespace_YourModule" setup_version="2.0.0" />

</config>

If you are not sure which module is creating this problem, you can try removing each module and check to find the problematic module.

Solution 2:

If solution 1 doesn’t help then you can try this second solution.

Give full control (read/write/execute) to var and pub directory solved this issue for me.

sudo chmod -R 777 var pub

You may also try running the following command:

sudo php -f bin/magento module:enable --clear-static-content YourNamespace_YourModule

Reference: http://blog.chapagain.com.np/magento-2-invalidargumentexception-there-are-no-commands-defined-in-the-setup-namespace/

Area code not set: Area code must be set before starting a session.

If you're running the latest version this error could occur by database or sample data out dated. So you could re-install or remove it:

php bin/magento sampledata:remove
or
php bin/magento sampledata:reset
I was able to work around the issue by deleting the system_config_snapshot flag.

DELETE FROM flag WHERE flag_code = 'system_config_snapshot';

You must be using the interactive console to authenticate

[Composer\Downloader\TransportException]
  The 'https://repo.magento.com/packages.json' URL required authentication.
  You must be using the interactive console to authenticate

You need to setup your keys on auth.json file like:

{
    "http-basic": {
        "repo.magento.com": {
            "username": "YOUR PUBLIC KEY",
            "password": "YOUR PRIVATE KEY"
        }
    }
}

Create a installation by cli command

 php bin/magento setup:install --backend-frontname="admin" --key="admin" --session-save="files" --db-host="localhost" --db-name="magento" --db-user="root" --db-password="root" --base-url="https://dev.magento2/" --base-url-secure="https://dev.magento2/" --admin-user="andre" --admin-password="minhasenha" --admin-email="[email protected]" --admin-firstname="André" --admin-lastname="da Luz"

Reload a specific ui component by JS

require('uiRegistry').get('index = product_listing').source.reload()

Where product_listing is the ui_component name.

Pass values to a template (from a controller to a Block)

   public function execute()
   {
       $name = $this->getRequest()->getParam('name');

       /** @var \Magento\Framework\View\Result\Page $resultPage */
       $resultPage = $this->resultPageFactory->create();
       $resultPage->getLayout()->initMessages();
       $resultPage->getLayout()->getBlock('Clounce_hello')->setName($name);
       return $resultPage;
   }

Reference: https://www.clounce.com/magento/a-very-basic-magento-2-module-with-parameterized-template

Updating Magento Version

 composer require magento/product-community-edition 2.2.3 --no-update
 composer update

When less file is not compiled

You need to look on pub/static and var/view_processed files.

Error Re generate css file in pub/static folder

Error to read file "file_get_contents()"

You need to look on the theme table and on core_config_data with path like '%theme%' if the theme_id is right. After fix it you need to run the setup:upgrade and then run the deploy.

alias mage="php -d memory_limit=-1 -f bin/magento"

chmod -R 775 pub/static/ var/ pub/media/ &&
rm -rf var/view_preprocessed/ var/cache/ var/page_cache/ var/tmp/ var/generation/ pub/static/frontend/ ;
mage cache:flush &
mage indexer:reindex &
mage setup:upgrade &&
mage setup:static-content:deploy ; 
mage setup:db-data:upgrade &&
mage dev:source-theme:deploy &&
chmod -R 775 pub/static/ pub/media/ var/

Clean cache after css modifications

rm -rf var/* && rm -rf pub/static/* && rm -rf generated/* && bin/magento cache:flush

Load products on cli command/programmatically

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('global');
 
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
 
$id = 1; // YOUR PRODUCT ID;
$sku = '24-MB01'; // YOUR PRODUCT SKU
 
// get product by product id
$product = $productRepository->getById($id); 
 
// get product by product sku
$product = $productRepository->get($sku);

-------------
$caseServices = $objectManager->get('\Magento\Signifyd\Model\CaseServices\CreationService');
$caseServices->createForOrder(5300);

Find field error

Search for admin__field-error text as it shows trough javascript/knockout automatically. When you can't save products on admin normally there is some invalid field hidden. It can be on advance price or advance stock config.

Debug custom controller 404 not working

Check \Magento\Framework\App\Router\ActionList::get (by setting a breakpoint) whether your controller class is actually instance of \Magento\Framework\App\ActionInterface - typos in namespace and use statements can prevent that - and it silently falls back to 404

Extend JS/Javascript or custom scripts

<sequence> tag to ensure that needed files from other components are already loaded when your component loads

USING MIXINS

Magento 2 has a lesser known feature called a require-js mixin that's useful for extending a js module from multiple places.

Your requirejs-config.js should look like:

var config = {
    'config': {
        'mixins': {
            'Magento_ConfigurableProduct/js/configurable': {
                'Vendor_AModule/js/configurable': true
            }
        }
    }
};

The js file would then be:

define([
    'jquery',
    'mage/translate'
], function ($) {

    return function (widget) {
        $.widget('vendor.configurable_awidget', widget, {
            /**
             * {@inheritDoc}
             */
            _configureElement: function (element) {
                this._super(element);
                alert('Custom widget A is triggered!');
            }
        });
        return $.vendor.configurable_awidget;
    };
});

This js returns a function which takes the target module as an argument and returns the extended version. This way you can extend the widget in different places without undesired overriding.

Declare the Module B

Because the A widget was "overridden" the default Magento widget already. So, in the Module B, we need to load the A widget and "override" it. app/code/Vendor/BModule/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            configurable : 'Vendor_BModule/js/configurable'
        }
    }
};

app/code/Vendor/BModule/view/frontend/web/js/configurable.js

define([
    'jquery',
    'mage/translate',
    'Vendor_AModule/js/configurable' // Module A widget
], function ($) {
    $.widget('vendor.configurable_bwidget', $.vendor.configurable_awidget, {
        /**
         * {@inheritDoc}
         */
        _configureElement: function (element) {
            this._super(element);
            alert('Custom widget B is triggered!');
        }
    });

    return $.vendor.configurable_bwidget;
});

After all, we need to run static content deploy again.

We can read more here: https://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/#using-_super-and-_superapply-to-access-parents


Reference: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/javascript/custom_js.html#extend_js Reference: https://ipfs-sec.stackexchange.cloudflare-ipfs.com/magento/A/question/162299.html

Navigation / Mega menu missing when Varnish Cache is activated with Magento 2

In some cases when Varnish Cache is activated, due to a Magento 2 and Varnish issue, the navigation menu can disappear.

In order to solve this Magento issue, you can remove the TTL attribute (remove ttl="3600") from /vendor/magento/module-theme/view/frontend/layout/default.xml, and the navigation menu will appear.

For more details regarding this Magento 2 issue, please visit magento/magento2#3421

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment