How to dump all options for any attribute in Magento 2 programmatically?

The following code does not adhere to Magento’s developer recommendations. Using object manager in such a way externally is a TERRIBLE idea.

Comment out line number 2 and then run the script. Edit line 11 and put the attribute code you want to dump

<?php
header("Location: /");exit;
use \Magento\Framework\App\Bootstrap;
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('./app/bootstrap.php');
$bootstrap     = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'manufacturer');
$options   = $attribute->getSource()->getAllOptions();
$options   = array_slice($options, 1);
usort($options, function($a, $b)
{
    return strcasecmp($a['label'], $b['label']);
});
if (count($options))
    $v = "<table>";
foreach ($options as $option) {
    $v .= "<tr><td>" . $option['value'] . '</td><td>' . $option['label'] . '</td></tr>';
}
if (count($options))
    $v .= "</table>";
echo $v;
?>
   <style>
    table tr:nth-child(odd){background:#444;color:#fff}
   </style>

How to customize Magento 2 Maintenance mode page?

Edit the file pub/errors/default/503.phtml and put the following code

<?php
/**
 * How to edit and customize code of Magento 2 Maintenance 503 Page
 * Add analytics if any
 * Replace <COMPANY NAME> with your Organization Name
 */
?>
<!doctype html>
<title>Site Maintenance</title>
<style>
  body { text-align: center; padding: 150px; }
  h1 { font-size: 50px; }
  body { font: 20px Helvetica, sans-serif; color: #333; }
  article { display: block; text-align: left; width: 650px; margin: 0 auto; }
  a { color: #dc8100; text-decoration: none; }
  a:hover { color: #333; text-decoration: none; }
</style>

<article>
    <h1>We&rsquo;ll be back soon!</h1>
    <div>
        <p>Sorry for the inconvenience but we&rsquo;re performing some maintenance at the moment. If you need to you can always <a href="mailto:[email protected] NAME">contact us</a>, otherwise we&rsquo;ll be back online shortly!</p>
        <p>&mdash; Team COMPANY NAME</p>
    </div>
</article>

How to hide a specific category from Google Index in Magento 2?

In Magento Admin Panel, Go to Catalog in Left Menu > Categories
Select the category you want to edit and in Design Section > Layout Update XML, put this value:

<head>
    <meta name="robots" content="NOINDEX,NOFOLLOW"/>
</head>
How to add noindex nofollow on specific category page in Magento2

Save the category and then Clear the cache

Fix Magento 2 – php cli error on cpanel or other hostings

The problem:

On a fresh install of Magento2 on cpanel based hosting, you receive the following error while running any command on SSH

[[email protected] www]$ php bin/magento cache:clean
X-Powered-By: PHP/7.0.31
Content-type: text/html; charset=UTF-8

bin/magento must be run as a CLI application
[[email protected] www]$ php bin/magento setup:upgrade
X-Powered-By: PHP/7.0.31
Content-type: text/html; charset=UTF-8

bin/magento must be run as a CLI application

The Solution:

You have to point php to correct binary;
Use the following code in order:
First, open the file which can alter the runtime variables like .bash_profile or .bashrc

cd ~ ; nano .bash_profile
OR
cd ~ ;nano .bashrc

Go to last line and paste this (depending upon php version change ea-php71 or ea-php70):

alias php='/opt/cpanel/ea-php71/root/usr/bin/php'

Save the file and exit the editor.
Log out and login again OR use the following command

$ source ~/.bashrc

If you are not sure about current php version, use which php or php -v command. If you think the cpanel configuration is the issue, fix EasyApache 4 PHP cli issue. With this way you can fix the setting and enable the new php version

How to get all attributes with all available labels/options in Magento2?

I did a lot of research but could not find a solution for that. so gathered some info and created this code: (it is not the best way to do it, but it works – you can use it at least one time for quick results)
the values need to be transformed if you want to see them properly in csv

Here is how to print all available attributes in backend and along with their all available options aka labels

<?php
        use \Magento\Framework\App\Bootstrap;
        error_reporting(E_ALL);
        ini_set("display_errors",1);
        include('./app/bootstrap.php');
        $bootstrap = Bootstrap::create(BP, $_SERVER);
        $objectManager = $bootstrap->getObjectManager();
        //use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory;
        $collection= $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory')->create();
//$attr_groups = array();
$fta=array();
$ft=array();
        foreach ($collection as $items) {
                        $attr_groups = $items->getData();
                                                if($attr_groups['frontend_input']=="select" or $attr_groups['frontend_input']=="multiselect"){
$eav=$objectManager->get('\Magento\Eav\Model\Config')->getAttribute('catalog_product',$attr_groups['attribute_code'])->getSource()->getAllOptions();
$ft[]=$attr_groups['frontend_label'];
$ft[]=$attr_groups['attribute_code'];
//echo $attr_groups['attribute_code'].'<br>'.$attr_groups['frontend_input'].'<br>'.$attr_groups['frontend_label'].'<br>'.$attr_groups['attribute_id'].'<br>';
foreach($eav as $getlabel) {
        if(is_object($getlabel['label'])){
        $r = new ReflectionObject($getlabel['label']);
$p = $r->getProperty('text');
//echo $p;
$p->setAccessible(true);
        $ft[]= $p->getValue($getlabel['label']);
        }
        else
        $ft[]= $getlabel['label'];
}
$fta[]=$ft;
$ft=array();
}

Magento 2 all cli commands

[~/www]# php bin/magento list
Magento CLI version 2.2.4
Usage:
command [options] [arguments]
Options:
-h, --help            Display this help message
-q, --quiet           Do not output any message
-V, --version         Display this application version
--ansi            Force ANSI output
--no-ansi         Disable ANSI output
-n, --no-interaction  Do not ask any interactive question
-v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
help                                     Displays help for a command
list                                     Lists commands
admin
admin:user:create                        Creates an administrator
admin:user:unlock                        Unlock Admin Account
app
app:config:dump                          Create dump of application
app:config:import                        Import data from shared configuration files to appropriate data storage
cache
cache:clean                              Cleans cache type(s)
cache:disable                            Disables cache type(s)
cache:enable                             Enables cache type(s)
cache:flush                              Flushes cache storage used by cache type(s)
cache:status                             Checks cache status
catalog
catalog:images:resize                    Creates resized product images
catalog:product:attributes:cleanup       Removes unused product attributes.
config
config:sensitive:set                     Set sensitive configuration values
config:set                               Change system configuration
config:show                              Shows configuration value for given path. If path is not specified, all saved values will be shown
cron
cron:install                             Generates and installs crontab for current user
cron:remove                              Removes tasks from crontab
cron:run                                 Runs jobs by schedule
customer
customer:hash:upgrade                    Upgrade customer's hash according to the latest algorithm
deploy
deploy:mode:set                          Set application mode.
deploy:mode:show                         Displays current application mode.
dev
dev:di:info                              Provides information on Dependency Injection configuration for the Command.
dev:profiler:disable                     Disable the profiler.
dev:profiler:enable                      Enable the profiler.
dev:query-log:disable                    Disable DB query logging
dev:query-log:enable                     Enable DB query logging
dev:source-theme:deploy                  Collects and publishes source files for theme.
dev:template-hints:disable               Disable frontend template hints. A cache flush might be required.
dev:template-hints:enable                Enable frontend template hints. A cache flush might be required.
dev:tests:run                            Runs tests
dev:urn-catalog:generate                 Generates the catalog of URNs to *.xsd mappings for the IDE to highlight xml.
dev:xml:convert                          Converts XML file using XSL style sheets
i18n
i18n:collect-phrases                     Discovers phrases in the codebase
i18n:pack                                Saves language package
i18n:uninstall                           Uninstalls language packages
import
import:categories                        Run category importer script
indexer
indexer:info                             Shows allowed Indexers
indexer:reindex                          Reindexes Data
indexer:reset                            Resets indexer status to invalid
indexer:set-mode                         Sets index mode type
indexer:show-mode                        Shows Index Mode
indexer:status                           Shows status of Indexer
info
info:adminuri                            Displays the Magento Admin URI
info:backups:list                        Prints list of available backup files
info:currency:list                       Displays the list of available currencies
info:dependencies:show-framework         Shows number of dependencies on Magento framework
info:dependencies:show-modules           Shows number of dependencies between modules
info:dependencies:show-modules-circular  Shows number of circular dependencies between modules
info:language:list                       Displays the list of available language locales
info:timezone:list                       Displays the list of available timezones
maintenance
maintenance:allow-ips                    Sets maintenance mode exempt IPs
maintenance:disable                      Disables maintenance mode
maintenance:enable                       Enables maintenance mode
maintenance:status                       Displays maintenance mode status
module
module:disable                           Disables specified modules
module:enable                            Enables specified modules
module:status                            Displays status of modules
module:uninstall                         Uninstalls modules installed by composer
sampledata
sampledata:deploy                        Deploy sample data modules
sampledata:remove                        Remove all sample data packages from composer.json
setup
setup:backup                             Takes backup of Magento Application code base, media and database
setup:config:set                         Creates or modifies the deployment configuration
setup:cron:run                           Runs cron job scheduled for setup application
setup:db-data:upgrade                    Installs and upgrades data in the DB
setup:db-schema:upgrade                  Installs and upgrades the DB schema
setup:db:status                          Checks if DB schema or data requires upgrade
setup:di:compile                         Generates DI configuration and all missing classes that can be auto-generated
setup:install                            Installs the Magento application
setup:performance:generate-fixtures      Generates fixtures
setup:rollback                           Rolls back Magento Application codebase, media and database
setup:static-content:deploy              Deploys static view files
setup:store-config:set                   Installs the store configuration. Deprecated since 2.2.0. Use config:set instead
setup:uninstall                          Uninstalls the Magento application
setup:upgrade                            Upgrades the Magento application, DB data, and schema
store
store:list                               Displays the list of stores
store:website:list                       Displays the list of websites
theme
theme:uninstall                          Uninstalls theme
varnish
varnish:vcl:generate                     Generates Varnish VCL and echos it to the command line

Installing Magento Common Issues

Following are the steps to complete install Magento error-free:-

  • Uncomment the files which are required by Magento in php.ini and restart the server
  • If installation error occurs, set memory_limit = 786M
  • if still error occurs, uninstall the db and make it again
  • after successfull install, go to (root_directory)app/etc/di.xml and change “Symlink” to “Copy” in¬†developerMaterialization section.
  • go to cmd , root directory¬†and type :- “/bin/magento setup:static-content:deploy
  • refresh the page. done.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry Magento 2

SELECT u.value_id,u2.value_id, u.attribute_id, u.entity_id, u.value
FROM catalog_product_entity_int u, catalog_product_entity_int u2
WHERE u.entity_id = u2.entity_id AND u.attribute_id = u2.attribute_id AND u.value= u2.value and u.value_id<u2.value_id
DELETE FROM catalog_product_entity_int
WHERE value_id IN (
SELECT u.value_id as value_id
FROM catalog_product_entity_int u, catalog_product_entity_int u2
WHERE u.entity_id = u2.entity_id AND u.attribute_id = u2.attribute_id AND u.value= u2.value and u.store_id=u2.store_id and u.value_id<u2.value_id
)

How to tweak Magento 2 for two letter search in fulltext mode

The problem:

Magento 2 wont return any search results if the search token is 2 letters in length.

Solution:

Alter MySQL conf file. Edit my.cnf file on your server
In CentOS, use command

nano /etc/my.cnf

and add the following lines:

ft_min_word_len=2
innodb_ft_min_token_size=2

Save using CTRL+x and then restart mysqld service.
Now we need to regenerate the index in order to get updated search results. Use the following SQL commands to regenerate:

Don’t forget to replace “jack_db1” with your database name

ALTER TABLE `jack_db1`.`catalogsearch_fulltext_scope1` DROP PRIMARY KEY, ADD PRIMARY KEY (`entity_id`, `attribute_id`) USING BTREE;
ALTER TABLE `jack_db1`.`catalogsearch_fulltext_scope1` DROP INDEX `FTI_FULLTEXT_DATA_INDEX`, ADD FULLTEXT `FTI_FULLTEXT_DATA_INDEX` (`data_index`);
ALTER TABLE `jack_db1`.`catalog_eav_attribute` DROP PRIMARY KEY, ADD PRIMARY KEY (`attribute_id`) USING BTREE;
ALTER TABLE `jack_db1`.`catalog_eav_attribute` DROP INDEX `CATALOG_EAV_ATTRIBUTE_USED_IN_PRODUCT_LISTING`, ADD INDEX `CATALOG_EAV_ATTRIBUTE_USED_IN_PRODUCT_LISTING` (`used_in_product_listing`) USING BTREE;
ALTER TABLE `jack_db1`.`catalog_eav_attribute` DROP INDEX `CATALOG_EAV_ATTRIBUTE_USED_FOR_SORT_BY`, ADD INDEX `CATALOG_EAV_ATTRIBUTE_USED_FOR_SORT_BY` (`used_for_sort_by`) USING BTREE;

References:
https://magento.stackexchange.com/a/157478/32283
https://dev.mysql.com/doc/refman/5.7/en/fulltext-fine-tuning.html