Wednesday 23 November 2016

Magento remove shipping methods if free shipping available

The following code will hide the other shipping methods from the shopping cart page, the default magento checkout and one page checkout.

The file you need to adjust is:

app/ design/ frontend/ default/YOURTEMPLATE/ template/ checkout/ onepage/ shipping_method/ available.phtml

<?php if ( array_key_exists('freeshipping', $_shippingRateGroups )) { $_shippingRateGroups = array('freeshipping' => $_shippingRateGroups['freeshipping']); } ?>

place this code right before the <dl> tag that displays the different options.

Friday 18 November 2016

Magento how to get first item or last item from the collection ?

$collection->getFirstItem() and $collection->getLastItem();

Magento how will you log current collection’s SQL query?

$collection->printLogQuery(true); OR $collection->getSelect()->__toString();

Magento where is the relation between configurable product and it’s simple product stored in database?

In the 2 tables:

1. catalog_product_relation
2. catalog_product_superlink_table

What can you do to optimize Magento performance?

Tweak .htaccess for performance optimization in Magento. It will not sky rocket your website, but will show notable improvement. The default Magento .htaccess comes with performance optimization, but commented by default. I will show you here which lines to uncomment and improve the performance.

Compressing web pages with mod_deflate

The mod_deflate module allows the Apache2 web service to compress files and deliver them to browser that can handle them. With mod_deflate you can compress HTML, text or XML files by upto 70% of their original sizes! Thus, saving you server traffic and speeding up page loads.

Check your .htaccess file for below code, I have removed hashes before few lines to uncomment them for performance.

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary

</IfModule>

Enabling expires header with mod_expires

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
ExpiresActive On
    ExpiresDefault "access plus 1 year"

</IfModule>

What are the different design patterns used in Magento?

Factory:
It implement the concept of factories and deals with the problem of creating objects without specifying the exact class of object that will be created.

1 $product = Mage::getModel('catalog/product');

Singleton:

It restricts the instantiation of a class to one object. It will refer to same object each time called.
1 $category = Mage::getSingleton('catalog/session');

Registry:

It is a way to store information throughout your application.
Mage::register('key',$value); //stores
$currentCategory = Mage::registry('key'); //retrives

Prototype:

It determines the type of object to create. In Magento it can be Simple, Configurable, Grouped, Bundle, Downloadable or Virtual types.

Mage:getModel('catalog/product')->getTypeInstance();

Observer:

It is mainly used to implement distributed event handling systems. Here the subject maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Mage::dispatchEvent('event_name', array('key'=>$value));
<config>
    <global>
        <events>
            <event_name>
                <observers>
                    <unique_name>
                        <class>Class_Name</class>
                        <method>methodName</method>
                    </unique_name>
                </observers>
            </event_name>
        </events>
    </global>
</config>

Object Pool:

It is used to reuse and share objects that are expensive to create.
$id = Mage::objects()->save($object);
$object = Mage::objects($id);

Iterator:

It is used to traverse a collection and access the collection’s items.
Mage::getModel('catalog/product')->getCollection();

Lazy Loading:

It is used to defer initialization of an object until the point at which it is needed.
$collection_of_products = Mage::getModel('catalog/product')
->getCollection();

Helper:

Multiple methods are available for use by other objects. Here you can use core’s helper methods from anywhere in the application.
Mage::helper('core');

Service Locator:

Allows overrides or renamed physical resources (e.g. Classes, DB tables, etc)
Mage::getModel('catalog/product') and $installer->getTable('customer/address_entity');

Magento what are the commonly used block types? What is the special in core/text_list block type.

Commonly used block types: core/template, page/html, page/html_head, page/html_header, page/template_links, core/text_list, page/html_wrapper, page/html_breadcrumbs, page/html_footer, core/messages, page/switch.

Some blocks like content, left, right etc. are of type core/text_list. When these blocks are rendered, all their child blocks are rendered automatically without the need to call getChildHtml() method.

Explain different types of sessions in Magento and the reason why you store data in different session types?

Customer sessions stores data related to customer, checkout session stores data related to quote and order. They are actuall under one session in an array. So firstname in customer/session will be $_SESSION['customer']['firstname'] and cart items count in checkout/session will be $_SESSION['checkout']['items_count']. The reason Magento uses session types separately is because once the order gets placed, the checkout session data information should get flushed which can be easily done by just unsetting $_SESSION['checkout'] session variable. So that the session is not cleared, just session data containing checkout information is cleared and rest all the session types are still intact.

How many database tables will Magento create when you make a new EAV module?

Magento creates 6 tables when you create new EAV module. Tables: module, module_datetime, module_decimal, module_int, module_text and module_varchar. one is the main entity table, and rest 5 tables which holds attribute’s data in different data types. So that integer values will go to module_int table, price values to module_decimal, etc.

What are magic methods in Magento?

Magento uses __call(), __get(), __set(), __uns(), __has(), __isset(), __toString(), __construct(), etc. magic methods. You can find more details inside class Varien_Object

How will you enable maintenance mode of your Magento website?

If you want your Magento website to show in maintenance mode, you will have to do two things.

1. Create a file name maintenance.flag in your magento root directory. Contents under this file doesn’t matter, you can keep it empty.

2. Change the maintenance file (located in magento root -> errors -> default directory) to show proper message when user visits your website.

How will you join flat table and EAV table in Magento?

Joining tables in Magento when it comes to EAV with Flat table is quite complicated. Consider you want to join sales_flat_order table with customer EAV tables to get Customer’s firstname and lastname, it becomes difficult as customer’s name comes from customer_entity_varchar table.

Below code will join sales order flat table with customer EAV to get customer’s full name in the collection along with all the order details.
$coll = Mage::getModel('sales/order')->getCollection();


$fn = Mage::getModel('eav/entity_attribute')->loadByCode('1', 'firstname');
$ln = Mage::getModel('eav/entity_attribute')->loadByCode('1', 'lastname');


$coll->getSelect()
    ->join(array('ce1' => 'customer_entity_varchar'), 'ce1.entity_id=main_table.customer_id', array('firstname' => 'value'))
    ->where('ce1.attribute_id='.$fn->getAttributeId())
    ->join(array('ce2' => 'customer_entity_varchar'), 'ce2.entity_id=main_table.customer_id', array('lastname' => 'value'))
    ->where('ce2.attribute_id='.$ln->getAttributeId())
    ->columns(new Zend_Db_Expr("CONCAT(`ce1`.`value`, ' ',`ce2`.`value`) AS fullname"));


print_r($coll->getData());

Magento can you have more than one Grid in a module?

Yes

Magento how will you add/remove content from core’s system.xml file?

You can do that by overriding system.xml configuration. Examples:

<config>
    <sections>
        <catalog>
            <groups>
                <frontend>
                    <label>Overriding Catalog Frontend in system config</label>
                </frontend>
            </groups>
        </catalog>
    </sections>
</config>
-------------------------------------------------------------------------------------------------------------------

<config>
   <sections>
        <payment>
            <groups>
                <cashondelivery>
                    <fields>
                        <!--changing cashondelivery payment method settings-->
                    </fields>
                </cashondelivery>
            </groups>
         </payment>
    </sections>
</config>

How will you override Block/Model/controllers in Magento?

After spending many hours in rewriting block and controller of Magento core module, I finally came up with a solution.

Here I am going to rewrite block: Mage/Adminhtml/Block/Sales/Shipment/Grid.php
and controller: Mage/Adminhtml/controllers/Sales/ShipmentController.php
First you will need to make a xml file for your new module at app/etc/modules directory
CompanyName_Adminhtml.xml

<?xml version="1.0"?>
<config>
    <modules>
        <CompanyName_Adminhtml>
            <active>true</active>
            <codePool>local</codePool>
        </CompanyName_Adminhtml>
    </modules>
</config>

Then, make folders in your app/code/local directory as follows:

- CompanyName
-> Block
—> Sales
—-> Shipment
——> Grid.php
-> controllers
—> Sales
—-> ShipmentController.php
-> etc
—> config.xml

In etc/config.xml, your code should look like below:


<?xml version="1.0"?>
<config>
    <modules>
        <CompanyName_Adminhtml>
            <version>0.1.0</version>
        </CompanyName_Adminhtml>
    </modules>

    <global>
    <blocks>
        <adminhtml>
            <rewrite>
             
<sales_shipment_grid>CompanyName_Adminhtml_Block_Sales_Shipment_Grid</sales_shipment_grid>
            </rewrite>
        </adminhtml>
    </blocks>

    <routers>
            <adminhtml>
           <rewrite>
                  <sales_shipment>
                      <from><![CDATA[#^/admin/sales_shipment/$#]]></from>
                      <to>/admin/sales_shipment/</to>
                  </sales_shipment>
            </rewrite>
       </adminhtml>
        </routers>
   </global>


    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <CompanyName_Adminhtml before="Mage_Adminhtml">CompanyName_Adminhtml</CompanyName_Adminhtml>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>

</config>


In ShipmentController.php, you should start like this:

require_once("Mage/Adminhtml/controllers/Sales/ShipmentController.php");
class CompanyName_Adminhtml_Sales_ShipmentController extends Mage_Adminhtml_Sales_ShipmentController
{
  //controller methods goes here..
}

require_once is necessary as magento is not going to load controllers as it does for blocks and models.

In block Grid.php, start the file like below:

class CompanyName_Adminhtml_Block_Sales_Shipment_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
  // block methods goes here..
}

That’s it! Now you should get your local Grid.php and ShipmentController.php loading instead of core’s

Is it mandatory to give Namespace while creating custom module in Magento?

No

Magento difference between EAV and flat model ?

EAV is entity attribute value database model, where data is fully in normalized form. Each column data value is stored in their respective data type table. Example, for a product, product ID is stored in catalog_product_entity_int table, product name in catalog_product_entity_varchar, product price in catalog_product_entity_decimal, product created date in catalog_product_entity_datetime and product description in catalog_product_entity_text table. EAV is complex as it joins 5-6 tables even if you want to get just one product’s details. Columns are called attributes in EAV.

Flat model uses just one table, so it’s not normalized and uses more database space. It clears the EAV overhead, but not good for dynamic requirements where you may have to add more columns in database table in future. It’s good when comes to performance, as it will only require one query to load whole product instead of joining 5-6 tables to get just one product’s details. Columns are called fields in flat model.

Magento how will you enable product’s custom attribute visibility in frontend?

In the Manage Attributes section of the custom attribute, select Visible on Product View Page on Front-end and Used in Product Listing to Yes.

When will you need to clear cache to see the changes in Magento?

When you have added/modified XML, JS, CSS file(s).

What is codePool in Magento?

codePool is a tag which you have to specify when registering new module in app/etc/modules/Company_Module.xml

There are 3 codePools in Magento: core, community and local, which are resided at app/code/ directory.

Core codePool is used by Magento core team, Community is generally used by 3rd party extensions and Local codePool should be used for in-hour module development and overriding of core and community modules for custom requirement.

So in short, codePool helps Magento to locate module inside app/code/ for processing.

Magento how will you call a CMS block in your module’s PHTML file?

$this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘blockidentifier’)->toHtml();

Difference between Mage::getSingleton() and Mage::getModel() in magento

The difference between Mage:getSingleton() and Mage::getModel() is that the former one does not create an object if the object for same class is already created, while the later creates new objects every time for the class when it’s called.

Mage::getSingleton() uses the “singleton design pattern” of PHP. If the object is not created, it will create it.

Mage::getSingleton() is mostly used when you want to create an object once, modify it and later fetch from it. Popular example is session, you first create a session object, and then add/remove values from session across different pages, so that it retains your values (e.g. cart values, logged in customer details, etc.) and doesn’t create new session object losing your last changes.

Mage::getModel() is used when you want to have the fresh data from the database. Example is when you want to show records from database.

What is EAV in Magento?

EAV, stands for Entity Attribute Value, is a technique which allows you to add unlimited columns to your table virtually. Means, the fields which is represented in “column” way in a regular table, is represented in a “row” (records) way in EAV. In EAV, you have one table which holds all the “attribute” (table field names) data, and other tables which hold the “entity” (id or primary id) and value (value for that id) against each attribute.

In Magento, there is one table to hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form,

- eav_entity, eav_entity_int (for holding Integer values),
- eav_entity_varchar (for holding Varchar values),
- eav_entity_datetime (for holding Datetime values),
- eav_entity_decimal (for holding Decimal/float values),
- eav_entity_text (for holding text (mysql Text type) values).

EAV is expensive and should only be used when you are not sure about number of fields in a table which can vary in future. To just get one single record, Magento joins 4-5 tables to get data in EAV. But this doesn’t mean that EAV only has drawbacks. The main advantage of EAV is when you may want to add table field in future, when there are thousands or millions of records already present in your table. In regular table, if you add table field with these amount of data, it will screw up your table, as for each empty row also some bytes will be allocated as per data type you select. While in EAV, adding the table column will not affect the previously saved records (also the extra space will not get allocated!) and all the new records will seamlessly have data in these columns without any problem.

How Magento ORM works?

ORM stands for Object Relational Mapping. It’s a programming technique used to convert different types of data to Objects and vice versa.

In Magento, ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.

- First is the “simple” i.e. Regular Models which is nothing but flat table or our regular table structure.
- Second Model is EAV (Entity Attribute Value), which is quite complicated and expensive to query.

All Magento Models interacting with database are inherited from Mage_Core_Model_Abstract class, which is further inherited from Varien_Object.

Difference between two Models is, Simple Model is inherited from Mage_Core_Model_Resource_Db_Abstract class,
while EAV is inherited from Mage_Eav_Model_Entity_Abstract.

For those who don’t know what EAV is, please read my 3rd answer below.

So, to end up this question,
when you want to get some data in Magento, you call it like this:
1 Mage::getModel('module/model')->load(1);
where 1 is the primary key id for some Regular/Simple table, while in EAV so many tables are joined to fetch just single row of data.

Explain Magento MVC architecture.

What is MVC?

MVC stands for Model-View-Controller. Any application that separates it’s data access, business logic and user interface is called MVC. There can be two types of MVC: convention-based and configuration-based. Example, cakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines. Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has controllers (for request/response routing), Block (for rendering content), Model (for business logic), Resource/Mysql4 (for database operations), etc (for module-specific configuration files), Helper (for common functions), sql (for setup scripts), layout (for connecting block with templates for each controller action) and template/.PHTML file (for Presentation i.e. View).

MVC in Magento:-

1. When you enter the URL (something like http://loca.lho.st/frontname/controller/method/param1/value1/param2/value2), this URL is intercepted by one PHP file called index.php which instantiates Magento application

2. Magento application instantiates Front Controller object.

3. Further, front controller instantiates Router objects (specified in module’s config.xml, global tag).

4. Now, Router is responsible to “match” the frontname which is in our URL.

5. If “match” is found, it sees controller name and method name in the URL, which is finally called.

6. Now depending on what is written in action name (method name), it is executed. If any models are called in it, the controller method will instantiate that model and call the method in it which is requested.

7. Then the controller action (method) instantiate the Layout object, which calls Block specified for this action (method) name (Each controller action name have block and template file associated with it, which can be found at app/design/frontend or adminhtml/namespace/module/layout/module.xml file, name of layout file (module.xml) can be found in config.xml of that module, in layout updates tag).

8. Template file (.phtml) now calls the corresponding block for any method request. So, if you write $this->methodName in .phtml file, it will check “methodName” in the block file which is associated in module.xml file.

9. Block contains PHP logic. It references Models for any data from DB.
10. If either Block, Template file or Controller need to get/set some data from/to database, they can call Model directly like Mage::getModel(‘modulename/modelname’).


Magento add toolbar and pager to custom product collection

Magento add toolbar and pager to custom product collection

Create toolbar object like:-

$toolbar = Mage::getBlockSingleton("catalog/product_list")->getToolbarBlock();

Then Assign product collection to toolbar object :-

$toolbar->setCollection($_productCollection);
$layout = Mage::getSingleton("core/layout");

Then set pager to toolbar as a child for show with pagination:-

$pager = $layout->createBlock("page/html_pager");

$toolbar->setChild("product_list_toolbar_pager", $pager);
echo $toolbar->toHtml();  

Wednesday 2 November 2016

How to place top menu to left side bar in magento 2

<referenceContainer name="sidebar.main">
<block class="Magento\Framework\View\Element\Template" name="store.menu" group="navigation-sections" template="Magento_Theme::html/container.phtml">
<arguments>
<argument name="title" translate="true" xsi:type="string">Menu</argument>
</arguments>
</block>
</referenceContainer>

Magento call newsletter in sidebar

Add below code in <body> tag in module-newsletter/view/frontend/layout/default.xml :-


You can use sidebar.main instead of sidebar.additional  for show in top of sidebar :-

<referenceContainer name="sidebar.additional">
            <block class="Magento\Newsletter\Block\Subscribe" name="form.subscribe" as="subscribe" after="wishlist_sidebar" template="subscribe.phtml"/>
        </referenceContainer>

Magento redirect to subdomain on mobile view

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  window.location="http://m.hostname.com";
}
</script>

magento get stock information of product

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

You can check stock data in this way:-

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

Or, you can print individually like this:-

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