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.

Magento2 call cms static block

 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

If you want to call cms block in .phtml template file then add below code to your phtml file –

<?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('a2bizz_block_identifier')->toHtml();?>

If you want to call cms block in .xml file, then add below code to the layout file –

<referenceContainer name="content">
  <block class="Magento\Cms\Block\Block" name="a2bizz_block_identifier">
   <arguments>
     <argument name="a2bizz_block_id" xsi:type="string">a2bizz_block_identifier</argument>
   </arguments>
 </block>
</referenceContainer>

If you want to call cms block in CMS Page

{{block class="Magento\\Cms\\Block\\Block" block_id="a2bizz_block_identifier"}}

Magento2: create custom module

Today we will learn to create custom module in magento2-

For installation and initial learning please visit our previous blogs of magento2.

The overall development we are doing on Ubuntu 14.4, local environment the base directory structure of my local is –
/var/www/html/magento2/app/code/A2bizz/Blog

You can download full code from GIT below given URL –
https://github.com/bloga2bizz/Magento2-Sample-Frontend-Module

customModule

Step 1.Initialization of your custom module –

First of all we will have to initialize our custom module to the list of modules with magento configuration, for which we will have to first create a /var/www/html/magento2/app/code/A2bizz/Blog/registration.php file and write below code –

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'A2bizz_Blog',
__DIR__
);

?>

if you hit your magento2 URL i.e. http://localhost/magento2/, now you will get below issue –

Cannot read contents from file "/var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml"

Now create module.xml on file /var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml and write below code –

<?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="A2bizz_Blog" setup_version="2.0.0" />
</config>

Now we have initialised our custom module, To check that please check /var/www/html/magento2/app/etc/config.php where your created module will be listed down, if not then upgrade custom module.

Step 2. creating controller & routing –

Now Further create controller file /var/www/html/magento2/app/code/A2bizz/Blog/Controller/Index/Index.php

<?php

namespace A2bizz\Blog\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{    
	protected $resultPageFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $resultPageFactory
	)
	{
		$this->resultPageFactory = $resultPageFactory;
		parent::__construct($context);
	}
    
    public function execute()
    {
        return $this->resultPageFactory->create();
    }

}

and a routes.xml file on path /var/www/html/magento2/app/code/A2bizz/Blog/etc/frontend/routes.xml,which will provide the path execution to your custom module –

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="blog" frontName="blog">
            <module name="A2bizz_Blog" />
        </route>
    </router>
</config>

here, in this xml we initializing the calling path for our custom module. In this way we have successfully hit out the controller for our custom module. Here in our example hit – http://127.0.0.1/magento2/blog

if the hitting above URL is showing blank white page, it means controller is hitted in a proper manner and now asking for the page layout.

Step 3. designing layout (view) for our custom module –

Now Further create layout files for your custom module /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/layout/blog_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="A2bizz\Blog\Block\Blog" name="blog" template="A2bizz_Blog::blog.phtml" />
        </referenceContainer>
    </body>
</page>

and add /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/templates/blog.phtml

<?php
echo "Blog Template";
?>

Now hit your custom module URL again, will show you below error
Object DOMDocument should be created.

it means it is unable to find corresponding Block method for its layout.

Now create your Block method, in /var/www/html/magento2/app/code/A2bizz/Blog/Block/Blog.php

<?php
namespace A2bizz\Blog\Block;

class Blog extends \Magento\Framework\View\Element\Template
{
	public function _prepareLayout()
	{
	    return parent::_prepareLayout();
	}
}
?>

Now, Executing your URL http://localhost/magento2/blog, will show you complete module functionality.