About Raj (MagePsycho)

Raj, the guy behind MagePsycho is a Zend PHP5 Certified Engineer, Magento Certified Developer, Magento Moderator / Freelancer with specialization in web applications (CMS, E-Commerce, ERP etc.). Catch him on: Twitter: @magepsycho Skype: magentopycho

Magento2: Fastest Way to Import / Update Product Prices in Bulk

March 19, 2017  |  No Comments  |  by Raj (MagePsycho)  |  Magento 2

Overview

As you know our Magento1 version of the script “Updating product prices in Magento in an easier & faster way” was a massive hit. And we are back with the similar script for Magento 2 which helps you to update the product prices in bulk – probably the easiest and fastest way possible.

Let’s take a look at the standalone PHP script & sample CSV file below:

How to run the script?

1. Prepare the Script

Copy/Paste the script from above to the file: [magento2-root]/pub/m2-import-prices-index.php

2. Prepare the CSV Data

Download the sample CSV file as “prices.csv” and update values for SKU & Price columns. Then upload the CSV file to the [magento2-root]/var/import/ directory.

3. Run the Script

You can run script either from browser or from CLI.

3.1 Executing the price bulk update from Browser
Go to the browser and hit the URL:
http://[magento2-base-url]/m2-import-prices-index.php

Which will out as below on successful operation:
Magento2 Bulk Price Update via Web

Note: If you are using Nginx web server and want to change the script filename other than *-index.php, you may need to edit the nginx.conf.sample file of Magento2 as

# PHP entry point for main application
location ~ (index|get|static|report|404|503|AddYourNewFileNameHere)\.php$ {

And of course need to reload the nginx configuration thereafter:

# Ubuntu
sudo service nginx reload

3.2 Executing the price bulk update script from CLI
Simply run the following command(s) from the Console of your server:

cd /path/to/magento2-root
php -f pub/m2-import-prices-index.php

Which will output as:
Magento2 Bulk Price Update via CLI

Note: This is recommended approach if you want to bulk update CSV data is big.

Hope Magento2 Developers & Store Owners will find this script useful.
Please do show your love towards the script by sharing & commenting below.

Bash Script: Create MySQL Database & User with Optional Password

January 3, 2017  |  No Comments  |  by Raj (MagePsycho)  |  Linux, Mysql

I have been using DigitalOcean for my personal projects. And one repeated things that I had to do is the creation of MySQL database & user. I know I could have used some CPanel like GUIs and even some of them came to my mind like VestaCP, Ajenti, ServerPilot etc. But all comes with sort of things and not so developer friendly.

So I decided to create a simple bash script that can simply the database & user.

Bash Script Code

You can find the script at Gist:

How to use?

1# Download
Download the script from Gist – Bash Script: Create MySQL Database & User

2# Set Permission
You need to set the executable permission in order to execute the shell script:

chmod +x mysql-create-db-user.sh

3# Usage
Use the script as:

./mysql-create-db-user.sh [--host="<host-name>"] --database="<db-name>" [--user="<db-user>"] [--pass="<user-password>"]

So the only required parameter is database name. In the case of empty values for other parameters:

  • ‘host’ becomes localhost
  • ‘user’ takes value from database name
  • ‘password’ is randomly generated

For the following command:

./mysql-create-db-user.sh --database=bash_db2

The output looks like:

Bash Script: Create MySQL Database & User with Optional Password

Bash Script Console: Create MySQL Database & User with Optional Password

Hope you find this script useful.
Please do let us know any feedback in the comments below.

How to set up multiple Magento 2 websites / stores with Nginx?

September 21, 2016  |  6 Comments  |  by Raj (MagePsycho)  |  Magento 2, Nginx

Magento is so flexible that one instance of it can have multiple websites/stores with different languages, domain names, categories etc.
You can configure the websites, stores, and store views in the Magento Admin. You use the MAGE_RUN_TYPE and MAGE_RUN_CODE variables in entry point scripts(index.php), .htaccess or Nginx configuration files(depending upon the web server you are using) to start the Magento application using these websites or store views.

Usage of MAGE_RUN_TYPE and MAGE_RUN_CODE

The code (i.e. MAGE_RUN_CODE and MAGE_RUN_TYPE) checks two environmental variables

$_SERVER['MAGE_RUN_TYPE']
$_SERVER['MAGE_RUN_CODE']

and use them to start Magento with the right website/store which can be defined in Manage Stores section in Admin.

The value of MAGE_RUN_TYPE determines if MAGE_RUN_CODE should be considered the code of a website or a store.

  • If MAGE_RUN_TYPE = ‘website’ is used, MAGE_RUN_CODE should be the code of the website and default store for this website will be loaded in the frontend.
  • If MAGE_RUN_TYPE = ‘store’ is used, MAGE_RUN_CODE should be the code of any store view and that particular store will be loaded in the frontend.

Nginx Configuration Settings

As mentioned before, there are many ways to configure the MAGE_RUN_TYPE and MAGE_RUN_CODE environment variables. But setting environment variables using web servers would be the best way as it doesn’t involve any core code edits.
Since I am using MEMP Stack, I will be sharing on how to configure Nginx for multi-website/store environment.

Case 1: One Website, Multiple Store Views

For example, we have

  • mystore.com (store code: mystore_en)
  • mystore.de (store code: mystore_de)
  • mystore.es (store code: mystore_es)

Step 1. Edit your Nginx virtual host configuration file as

File: Usually located under /etc/nginx/sites-available/ or /usr/local/etc/nginx/sites-available/ or other depending upon the OS type.

map $http_host $MAGE_RUN_CODE {
    mystore.com mystore_en;
    mystore.de mystore_de;
    mystore.es mystore_es;
}
server {
    listen 80;
    server_name mystore.com mystore.de mystore.es;
    set $MAGE_ROOT /path/to/your/magento2;
    set $MAGE_MODE default;
    include /path/to/your/magento2/nginx.conf.sample;
}

Here you can see how the Nginx map block is used to set MAGE_RUN_CODE as per host. And server_name directive includes all the available domains.

Step 2. Send MAGE_RUN_CODE and MAGE_RUN_TYPE variables to the php-fpm server
File: include path from above, example: path/to/your/magento2/nginx.conf.sample

#...
# PHP entry point for main application
location ~ (index|get|static|report|404|503)\.php$ {
    try_files $uri =404;
    fastcgi_pass   fastcgi_backend;
    fastcgi_buffers 1024 4k;

    fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
    fastcgi_param  PHP_VALUE "memory_limit=768M \n max_execution_time=600";
    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;
    
    #add here - start
    fastcgi_param  MAGE_RUN_TYPE store;
    fastcgi_param  MAGE_RUN_CODE $MAGE_RUN_CODE;
    #end

    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}
#...

Here Nginx fastcgi_param‘s MAGE_RUN_TYPE & MAGE_RUN_CODE will create the enviroment varilables for PHP, so that the script can access the values via

$_SERVER['MAGE_RUN_TYPE']
$_SERVER['MAGE_RUN_CODE']

Case 2: Multiple Website, Multiple Store views

For example, we have

  • mystore1.com (website code: mystore1)
    • mystore1.com (store code: mystore1_en)
    • mystore1.de (store code: mystore1_de)
    • mystore1.es (store code: mystore1_es)
  • mystore2.com (website code: mystore2)
    • mystore2.com (store code: mystore2_en)
    • mystore2.de (store code: mystore2_de)
    • mystore2.es (store code: mystore2_es)

In order to configure for this case, you can use the similar settings as for Case 1. The only difference will be the store code values for Nginx map block and domain names for server_name directive.

Conclusion

If you are unsure about which value(website or store) should you use for MAGE_RUN_TYPE, go for the store value and use the corresponding store code for MAGE_RUN_CODE

Hope this helps you in configuring the Nginx for multi-store/website. In the case of any issues with the multi-store setup, please do comment below.

Sandbox script for quick testing in Magento2

September 14, 2016  |  No Comments  |  by Raj (MagePsycho)  |  Linux, Mac OS-X, Magento 2

What’s your approach for quick & dirty testing in Magento2?

  • Creating a test module with a controller and executing it from browser to see the output?
  • Creating a Console module and executing via CLI?

Obviously, above two approaches takes time.

Rather I would create a simple script (a single file) and put it somewhere in /[path-to-magento2]/pub/sandbox.php

<?php
/**
 * @author Raj KB<magepsycho@gmail.com>
 * @website http://www.magepsycho.com
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

// Your quick and dirty code goes here...
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote()->load(1);
Zend_Debug::dump($quote->getOrigData());

Now you can easily test by pointing to URL
http://[magento2-url]/sandbox.php

But wait, this won’t work in the case when you are using Nginx + PHP-FPM server.
The reason you can explore from the Nginx conf file: [path/to/magento2]/nginx.conf.sample

...
# PHP entry point for main application
location ~ (index|get|static|report|404|503)\.php$ {
    try_files $uri =404;
    fastcgi_pass   fastcgi_backend;
    fastcgi_buffers 1024 4k;

    fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
    fastcgi_param  PHP_VALUE "memory_limit=768M \n max_execution_time=600";
    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;

    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}
...

As you can see only PHP files: index.php, get.php, static.php, report.php, 404.php & 503.php files are parsed by the PHP-FPM.

In order to include your sandbox.php in the whitelist, just edit the line of Nginx conf file:

location ~ (index|get|static|report|404|503)\.php$ {

to

location ~ (index|get|static|report|404|503|sandbox)\.php$ {

And don’t forget to reload or restart your Nginx server depending upon your Operating System.
Ubuntu

sudo service nginx reload
sudo service nginx restart

MacOSx

sudo nginx -s reload
sudo nginx -s stop && sudo nginx

What’s your approach for quick & dirty testing in Magento2? Please do comment below.

Magento 2: How the quantity_and_stock_status attribute value is populated in product object?

August 6, 2016  |  No Comments  |  by Raj (MagePsycho)  |  Magento 2

Well, a new product attribute that you may notice in Magento2 is quantity_and_stock_status.

SELECT * FROM eav_attribute WHERE attribute_code = 'quantity_and_stock_status';

Query Result:
quantity_and_stock_status attribute info

If you load a product object as:

$product = $this->_productRepository->getById($productId);
var_dump($product->getData());

You will see the value of quantity_and_stock_status as an array of is_in_stock and qty.
You must be thinking from where the heck it came from? These values are supposed to be in the stock item object.

Let’s dig it out.
Try to load any product:

$product = $this->_productRepository->getById($productId);

Inspect the value of following using X-Debug

$product->getData('quantity_and_stock_status')

You will notice that the value of quantity_and_stock_status is 1 initially (i.e. the default value).
Once the product is loaded, afterLoad() method of attribute’s backend_model: Magento\Catalog\Model\Product\Attribute\Backend\Stock is executed.

# Class: \Magento\Catalog\Model\Product\Attribute\Backend\Stock
/**
 * Set inventory data to custom attribute
 *
 * @param Product $object
 * @return $this
 */
public function afterLoad($object)
{
    $stockItem = $this->stockRegistry->getStockItem($object->getId(), $object->getStore()->getWebsiteId());
    $object->setData(
        $this->getAttribute()->getAttributeCode(),
        ['is_in_stock' => $stockItem->getIsInStock(), 'qty' => $stockItem->getQty()]
    );
    return parent::afterLoad($object);
}

From above you can see clearly that is_in_stock and qty value are being fed by the $stockItem object.
And hence scalar value becomes an array.
Now it’s no more mystery, right? Cool.

Now let’s comment on – “Why has Magento2 team introduced quantity_and_stock_status attribute?”