Magento 2 : Create custom logging

 

Magento 2 uses monolog library to log messages. You can check this library in following  path location in magento 2.

<magento_root_folder>/vendor/monolog/

Log file will be created inside var/log folder

If you want to use log in your custom module, you need to add instance of  monolog class in your custom file class. You need to pass the instance in the constructor of your custom class.

Go to app/code/yourCompany/yourModule/Block/custom.php

add following protected variable  in custom file class.

/**
* @var \Psr\Log\LoggerInterface
*/
protected $_logger;

add following parameter in your custom class  __construct()

\Psr\Log\LoggerInterface $logger

Now, we need to create an object

$this->_logger = $logger;
$this->_logger->addDebug('some text or variable');

Finally, constructor function looks like following

public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Cms\Model\Page $page,
        \Magento\Cms\Model\Template\FilterProvider $filterProvider,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Cms\Model\PageFactory $pageFactory,
        \Magento\Framework\View\Page\Config $pageConfig,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        parent::__construct($context, $data);
        // used singleton (instead factory) because there exist dependencies on \Magento\Cms\Helper\Page
        $this->_page = $page;
        $this->_filterProvider = $filterProvider;
        $this->_storeManager = $storeManager;
        $this->_pageFactory = $pageFactory;
        $this->pageConfig = $pageConfig;
        $this->_logger = $logger;
        $this->_logger->addDebug('some text or variable');
    }

Here is the use of some predefined examples :

$this->_logger->addDebug($message); // log location: var/log/system.log
$this->_logger->addInfo($message); // log location: var/log/exception.log
$this->_logger->addNotice($message); // log location: var/log/exception.log
$this->_logger->addError($message); // log location: var/log/exception.log
$this->_logger->critical($e); // log location: var/log/exception.log
You can also write to the logs using the zend library
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Your text message');

Magento 2 : Create customer group programmatically

Here is the way to add customer groups programmatically in Magento 2, use $group->save() on the model returned by the GroupFactory:

namespace A2bizz\MyCustomModule\Setup;
 
use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\GroupFactory;
 
class InstallData implements InstallDataInterface
{
    protected $groupFactory;
 
    /**
     * Customer group factory
     */
    public function __construct(GroupFactory $groupFactory) {
        $this->groupFactory = $groupFactory;
    }
 
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();
 
        // Create the new group
        /** @var \Magento\Customer\Model\Group $group */
        $group = $this->groupFactory->create();
        $group
            ->setCode('New Customer Group');
            ->setTaxClassId(3) 
            ->save();
 
        $setup->endSetup();
    }
}

Magento : Product stock quantity

From here you can get any product’s stock  quantity information like quantity (qty), minimum quantity (min_qty), stock availability (is_in_stock), minimum and maximum sale quantity (min_sale_qty and max_sale_qty).

Load Product

For that you need to load product. There are two ways to load product

1. Load by product id

$id = 12; // put custom product_id
$_product = Mage::getModel('catalog/product')->load($id);

2. Load by Product Sku

$sku = "bloga2bizz"; //custom product sku
 $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

 

Get Product stock information

$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);

You can check stock data in following way:-

echo "<pre>"; print_r($stock->getData()); echo "</pre>";

or

echo $stock->getQty();
echo $stock->getMinQty();
echo $stock->getMinSaleQty();

Magento : Fetch products with layered navigation programmatically in custom php file

 Buy cheap and genuine Windows 7 product key  |
 Windows 7 Product Key for Windows 32bit/64bit Updated 2016y  |
 Windows 7 Ultimate ISO download  |
 Windows 7 Product Key Generator 32 bit and 64 bit Full  |
 Legit Windows 7 Product Key Online Store, PayPal Support  |
 Windows 7 Ultimate with Service Pack 1 Product Key,Windows 7 Key Sale  |
 Windows 7 Key  |
 Get Free Windows 7 Product Key  |
windows-10-education-key
windows-10-enterprise-key
office-2010-key
windows-7-key-sale
windows-10-home-key
windows-10-activation-key
windows-10-pro-key
office-2016-key
windows-10-key
office-2013-key
windows-10-iso
windows-7-key
windows-10-product-key

Here is way to fetch products with layered navigation programmatically in custom php file.

<?php
require_once('app/Mage.php'); //Must have file to begin
 
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); //Initialize store
 
$catId = Mage::app()->getRequest()->getParam('categoryId'); //Pass categoryId in get variable
    $storeId = Mage::app()->getWebsite(true)->getDefaultGroup()->getDefaultStoreId();
    $page_no = Mage::app()->getRequest()->getParam('page_no');
    $params = Mage::app()->getRequest()->getParams(); //Pass attributes in key=>value form to filter results.
    $category = Mage::getModel('catalog/category')->load($catId);
 
    $layer = Mage::getModel("catalog/layer");
    $layer->setCurrentCategory($category);
    $attributes = $layer->getFilterableAttributes(); //get all filterable attributes available in selected category layered navigation
    $attr = array();
    foreach ($attributes as $attribute) {
        if ($attribute->getAttributeCode() == 'price') {
            $filterBlockName = 'catalog/layer_filter_price';
        } elseif ($attribute->getBackendType() == 'decimal') {
            $filterBlockName = 'catalog/layer_filter_decimal';
        } else {
            $filterBlockName = 'catalog/layer_filter_attribute';
        }
        $attr[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
 
    }
    $filters = array_intersect_key($params, $attr);
    $collection = $category->getProductCollection()
                    ->addAttributeToFilter(
                        'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
                    ->addAttributeToSelect('*');
    foreach ($filters as $key => $value) {
        if($key == 'price'){
            $priceFilter = explode('-', $value);
            $collection->addAttributeToFilter('price', array('gteq' => $priceFilter[0]));
            $collection->addAttributeToFilter('price', array('lteq' => $priceFilter[1]));
        }
        else{
            $collection->addAttributeToFilter($key, array('in' => $value));
        }
    }
    $collection->setPage($page_no, 10);
foreach($collection as $product){
   echo $product->getName();
}

Redirect functions in magento

Following redirect functions are present in app/code/core/Mage/Core/Controller/Varien/Action.php file.

  1. Redirect specific url : _redirectUrl($url);
  2. Redirect to specific path :  _redirect($path, $arguments=array());
  3. Success page redirection : _redirectSuccess($defaultUrl);
  4. Error page redirection : _redirectError($defaultUrl);
  5. Set referer url to redirect : _redirectReferer($defaultUrl=null);
  6. Get referer url via HTTP_REFERER, regular or requested param : _getRefererUrl()

Examples

In your controller class, you can use as follows

 $this->_redirect($path, $arguments=array());
 // or use,
 $this->_redirectUrl($url);

Here is another way,

//For simple url redirect:

 $url = "http://blog.a2bizz.com";
 Mage::app()->getFrontController()->getResponse()->setRedirect($url);

// Redirect with arguments
 Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl($path, $arguments));

Magento: Create Custom Module

Today, We are going learn to create custom module in Magento, so here are the below steps to create a sample ‘Helloworld’ module-

New Custom Module Creator for Magento2

Sample file structure:

[root]\app\code\local\{Namespace}\{Modulename}
[root]\app\code\local\{Namespace}\{Modulename}\controllers
[root]\app\code\local\{Namespace}\{Modulename}\etc
[root]\app\code\local\{Namespace}\{Modulename}\etc\config.xml
[root]\app\code\local\{Namespace}\{Modulename}\Helper
[root]\app\code\local\{Namespace}\{Modulename}\Model
[root]\app\code\local\{Namespace}\{Modulename}\{Modulename}.php

{Namespace} is a user defined variable. Basically it’s just a mechanism that allows the user to create disparate classes that would otherwise have the same names.

{Modulename} this is the name of your module.

controllers is where all the controllers go.

Model holds all of the models for your module.

For example we use “A2bizz” as namespace and “Helloworld” as Module. we entirely sure if it matters or not, but as a general rule we always capitalize the first letter and leave the rest lower case.

Step One

Inform Magento that you have a custom module. Note the file locations (need to create directories as necessary).

app/etc/modules/A2bizz_HelloWorld.xml

<?xml version=”1.0″?>
<config>
	<modules>
		<A2bizz_HelloWorld>
			<active>true</active>
			<codePool>local</codePool>
		</A2bizz_HelloWorld>
	</modules>
</config>

In this way we have informed Magento that we have an active module (you can turn it off from here by setting ‘active’ to false. we have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).

app/code/local/A2bizz/HelloWorld/etc/config.xml

<?xml version=”1.0″?>
<config>
	<global>
		<modules>
			<a2bizz_helloworld>
				<version>0.1.0</version>
			</a2bizz_helloworld>
		</modules>
		<blocks>
			<helloworld>
				<rewrite>
					<helloworld>A2bizz_HelloWorld_Block_HelloWorld</helloworld>
				</rewrite>
			</helloworld>
		</blocks>
	</global>
	<frontend>
		<routers>
			<helloworld>
				<use>standard</use>
				<args>
					<module>A2bizz_HelloWorld</module>
					<frontName>helloworld</frontName>
				</args>
			</helloworld>
		</routers>
		<layout>
			<updates>
				<helloworld>
					<file>helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>
	</frontend>
</config>

Here we informed Magento of module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

We aware Magento that module contains block files which are found in A2bizz/HelloWorld/Block. Here class name will have A2bizz_HelloWorld_Block. If you want to see the many possibilities of stuff that goes in here, check out Magento config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.

app/code/local/A2bizz/HelloWorld/Block/HelloWorld.php

<?php
class A2bizz_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
	public function _prepareLayout()
	{
		$this->getLayout()->getBlock(‘breadcrumbs’)
			->addCrumb(‘home’, array(‘label’=>Mage::helper(‘catalogsearch’)->__(‘Home’),
						‘title’=>Mage::helper(‘catalogsearch’)->__(‘Go to Home Page’),
						‘link’=>Mage::getBaseUrl())
						)
			->addCrumb(‘customer’, 
						array(‘label’=>Mage::helper(‘customer’)->__(‘Foo’))
						);
		return parent::_prepareLayout();
	}

	public function myMessage(){
		return “This is A2bizz, This is our module.”;
	}
}
?>

Step Four

Now we create a template file (.phtml) file.

app/design/frontend/default/default/template/helloworld/helloworld.phtml

<?php

echo ‘Hello World ! This A2bizz’;
echo “<BR/>”;
echo $this->myMessage();

?>

Now, Our custom module has been created you can use it, for additional functionality.

Magento 2: Set developer mode

Magneto supports a developer mode.

This is intended for internal development on a system already secured. During customizing the Magento Software, you should run magento software in developer mode.  It shows exceptions on screen instead of showing a generic error message like “There has been an error processing your request“.

In Developer mode :

  • Static view files are not cached, they are written to the Magento pub/static directory every time they’re called
  • Display uncaught exceptions in the screen.
  • System logging in var/report is verbose
  • An exception is thrown in the error handler, rather than being logged

Here is following way to setup developer mode :

1.  Add below line in  index.php

$_SERVER['MAGE_MODE'] = 'developer';

2. Run following command in terminal/command line :

bin/magento deploy:mode:set mode=developer

 

Static custom blocks short-codes are not working in Magento 1.9.2.2

 Buy cheap and genuine Windows 7 product key  |
 Windows 7 Product Key for Windows 32bit/64bit Updated 2016y  |
 Windows 7 Ultimate ISO download  |
 Windows 7 Product Key Generator 32 bit and 64 bit Full  |
 Legit Windows 7 Product Key Online Store, PayPal Support  |
 Windows 7 Ultimate with Service Pack 1 Product Key,Windows 7 Key Sale  |
 Windows 7 Key  |
 Get Free Windows 7 Product Key  |
windows-10-education-key
windows-10-enterprise-key
office-2010-key
windows-7-key-sale
windows-10-home-key
windows-10-activation-key
windows-10-pro-key
office-2016-key
windows-10-key
office-2013-key
windows-10-iso
windows-7-key
windows-10-product-key

Nowadays, most common question asked in magento community or stackexchange are “Static custom blocks short-codes are not working in Magento 1.9.2.2“. This issue arise due to following reason.

1. Update magento version to version 1.9.2.2
2. Installing patch SUPEE-6788

Example : I have include CMS static page as following

{{block type="cms/block" block_id="custom_static_block"}}

After updating this, “custom_static_block” is not displaying in home page. The shortcode also shows PHP error in log file under var folder.

Notice: Undefined variable: block  in /app/code/core/Mage/Core/Model/Email/Template/Filter.php on line xxx

I have checked and found that, All the custom static blocks are now working. This is new security patch SUPEE-6788. Custom static blocks need to added in whitelist.

More details technical regarding SUPEE-6788

The responsible code in Filter.php are given below :

if (isset($blockParameters['type'])) {
  if ($this->_permissionBlock->isTypeAllowed($blockParameters['type'])) {
    $type = $blockParameters['type'];
    $block = $layout->createBlock($type, null, $blockParameters);
  }
} elseif (isset($blockParameters['id'])) {
    $block = $layout->createBlock('cms/block');
    if ($block) {
     $block->setBlockId($blockParameters['id']);
   }
}

Now go to the System=> Permission => Blocks

System-permission->blocks

Simply you need to add block type which you have to add block with shortcode. Click on add new. Set block name Ex. “cms/block” and “is_allowed” to “yes”

System-permission->blocks

Now your static block will be in whitelisted and will be able to show in frontend.
div style=”display:none;”>
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |

Magento2 create custom theme

Today, We going to learn, how to create custom theme in magento2 , or how we can start to add our own customized theme, to do so, please follow the below steps –

1. Create the path app/design/frontend/a2bizz/custom, where a2bizz and custom are your own package and theme names respectively, whatever you like to give name, give it.

2. Now create a file theme.xml inside the above path, and write below given code –

<theme xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation = "../../../../../lib/internal/Magento/Framework/Config/etc/theme.xsd">
 <title>A2bizz Custom theme</title>
 <parent>Magento/blank</parent> <!--the parent theme, in case your theme inherits from an existing theme -->
 <media>
   <preview_image>media/preview.jpg</preview_image>
  </media>
</theme>

Now, register your theme and create a file registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/a2bizz/custom',
    __DIR__
);

Now, the registration of a custom theme is being completed and it has been added to the list of themes, go to the admin section and Select your custom theme from admin >> store >> Configuration >> General >> Design. to change the theme.