Friday 30 December 2016

How to disable dates in jQuery DatePicker

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  /* create an array of days which need to be disabled */
var array = ["2016-12-14","2016-12-15","2016-12-16","2017-02-16"];

$(function() {
    $("#datepicker").datepicker({
        beforeShowDay: function(date){
        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
        return [ array.indexOf(string) == -1 ]
    }
    });

});

  </script>
<body>
Date: <div id="datepicker"></div>
</body>

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();

Monday 18 July 2016

Get all parent category ids and self id in an array

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
  $current_cat = $category->getId(); // current category id

  $parent_cat =  $category->getParentCategory()->getId(); // parent category id
  foreach ($category->getParentCategories() as $parent) {
    $catids[] = $parent->getId(); // show all parent cat ids and self id in an array
}
if($catids[0]==parent_cat_id){
echo "show parent cat custom code";

}

magento 2 how to get parent category id current category

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
  $current_cat = $category->getId(); // current category id

  $parent_cat =  $category->getParentCategory()->getId(); // parent category id

magento 2 how to get current category id

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
  $current_cat = $category->getId(); // current category id

How to remove Default Magento 2 footer links

Step 1: Contact us
Go to \app\code\Magento\catalog\view\frontend\Layout\default.xml

Step 2: Remove footer links
For Privacy and Cookie Policy

Go to \app\code\Magento\Cms\view\frontend\Layout\default.xml

Comment block Line no- 13

<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current" name="privacy-policy-link">
<arguments>
<argument name="label" xsi:type="string">Privacy and Cookie Policy</argument>
<argument name="path" xsi:type="string">privacy-policy-cookie-restriction-mode</argument>
</arguments>
</block>
</referenceBlock>

For Search Terms

Go to app\code\Magento\Search\view\frontend\Layout\default.xml

Comment on block Line no- 13

<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current" ifconfig="catalog/seo/search_terms" name="search-term-popular-link"><arguments>
<argument name="label" xsi:type="string" translate="true">Search Terms</argument>
<argument name="path" xsi:type="string">search/term/popular</argument></arguments>
</block>
</referenceBlock>

For Orders and Returns

Go to app\code\Magento\Sales\view\frontend\Layout\default.xml

Comment block Line no- 16

<referenceBlock name="footer_links">
<block class="Magento\Sales\Block\Guest\Link" name="sales-guest-form-link">
<arguments>
<argument name="label" xsi:type="string">Orders and Returns</argument>
<argument name="path" xsi:type="string">sales/guest/form</argument></arguments>
</block>
</referenceBlock>

For Advanced Search

Go to app\code\Magento\CatalogSearch\view\frontend\Layout\default.xml

Comment block Line no- 13

<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current" name="catalog-search-advanced-link">
<arguments>
<argument name="label" xsi:type="string" translate="true">Advanced Search</argument>
<argument name="path" xsi:type="string">catalogsearch/advanced</argument><argument name="attributes" xsi:type="array">
<item name="data-action" xsi:type="string">advanced-search</item></argument>
</arguments>
</block>
</referenceBlock>

Magento 2 add custom footer

default.xml from module Magento\Theme add this code inside footer referenceContainer

<block class="Magento\Cms\Block\Block" name="block-footer" after="footer_links">
      <arguments>
            <argument name="block_id" xsi:type="string">block_footer_custom</argument>
      </arguments>

</block>


Goto backend Content > Blocks > Add new static block with identifier name block_footer_custom with any html code you need. It so easy to editable Clear cache and re-

deploy static. Now you will get your custom block

Custom jQuery use in magento 2

<script>
require(['jquery'],function($){ /*First call this function and after add your jQuery code*/

$( document ).ready(function() {
$(".navigation ul li").hover(function() {
    alert("hello");
});
});

});
</script>

magento call block in any where in page dynamically

Add xml in  Layout Update XML on Designs tab in cms page

<reference name="root">
<block type="bannerslider/default" name="bannerslider" template="bannerslider/bannerslider.phtml">
    <action method="setBannersliderId"><bannerslider_id>1</bannerslider_id></action>
</block>
</reference>

Add below code in any layout page (1column.phtml) where you want show

<?php echo $this->getChildHtml('bannerslider'); ?>

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


Add below code in <body> tag in Magento_Theme/view/frontend/layout/default.xml

<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 2 call newsletter in sidebar

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

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

        </referenceContainer>

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

Wednesday 22 June 2016

Google Maps Calculate Distance,Travel Duration, draw (plot) Route and display Directions between two locations

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
<script type="text/javascript">
        var source, destination;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        google.maps.event.addDomListener(window, 'load', function () {
            new google.maps.places.SearchBox(document.getElementById('txtSource'));
            new google.maps.places.SearchBox(document.getElementById('txtDestination'));
            directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        });

        function GetRoute() {
            var mumbai = new google.maps.LatLng(18.9750, 72.8258);
            var mapOptions = {
                zoom: 7,
                center: mumbai
            };
            map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('dvPanel'));

            //*********DIRECTIONS AND ROUTE**********************//
            source = document.getElementById("txtSource").value;
            destination = document.getElementById("txtDestination").value;

            var request = {
                origin: source,
                destination: destination,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

            //*********DISTANCE AND DURATION**********************//
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins: [source],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distance = response.rows[0].elements[0].distance.text;
                    var duration = response.rows[0].elements[0].duration.text;
                    var dvDistance = document.getElementById("dvDistance");
                    dvDistance.innerHTML = "";
                    dvDistance.innerHTML += "Distance: " + distance + "<br />";
                    dvDistance.innerHTML += "Duration:" + duration;

                } else {
                    alert("Unable to find the distance via road.");
                }
            });
        }
    </script>
<body onLoad="GetRoute();">
<table border="0" cellpadding="0" cellspacing="3">
  <tbody>
    <tr>
      <td colspan="2"> Source:
        <input type="text" id="txtSource" value="Behror, Rajasthan, India" style="width: 250px" placeholder="Enter a query" autocomplete="off">
        &nbsp;&nbsp; Destination:
        <input type="text" id="txtDestination" value="Jaipur, Rajasthan, India" style="width: 250px" placeholder="Enter a query" autocomplete="off">
        <br>
        <br>
        <input type="button" value="Get Route" onclick="GetRoute()">
        <hr></td>
    </tr>
    <tr>
      <td colspan="2"><div id="dvDistance"> </div></td>
    </tr>
    <tr>
      <td><div id="dvMap" style="width: 500px; height: 500px"> </div></td>
      <td><div id="dvPanel" style="width: 500px; height: 500px;overflow-y:auto"> </div></td>
    </tr>
  </tbody>
</table>
</body>

Monday 30 May 2016

Saturday 21 May 2016

detect browser language and redirect using javascript

When first time user open the site and detect browser language and redirect website according to languge using javascript.

 <script>
function GetCookie(name) {
        var arg=name+"=";
        var alen=arg.length;
        var clen=document.cookie.length;
        var i=0;

        while (i<clen) {
            var j=i+alen;
                if (document.cookie.substring(i,j)==arg)
                    return "here";
                i=document.cookie.indexOf(" ",i)+1;
                if (i==0)
                    break;
        }

        return null;
    }
$(function getck() {
    var visit=GetCookie("COOKIE1");
    if (visit==null){
        var userLang = navigator.language || navigator.userLanguage;
if(userLang=="fr"){
window.location='http://french.domain.com/';
}else if(userLang=="en-US"){
window.location='http://english.domain.com/';
}else{
window.location='http://domain.com/';
}
    }
    var expire=new Date();
    expire.setTime(expire.getTime()+(1*24*60*60*1000));
    document.cookie="COOKIE1=here; expires="+expire;
});
</script>

Saturday 7 May 2016

Detect when an HTML5 video finishes

<video id="myVideo" width="1349" height="758" preload="metadata" autoplay="1" controls>
<source src="http://id-cardz.com/wp-content/uploads/2016/05/upwork-damjikamran.mp4?_=1" type="video/mp4"></source>
</video>
<img id="myimg" onClick="playvid();" style="display:none;" src="image/path.jpg">
<a href="#" onClick="document.getElementById('myVideo').play();">Play video</a>
<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) { //on video stop ------------
        document.getElementById('myVideo').style.display = 'none';
        document.getElementById('myimg').style.display = 'block';
    }
    function playvid() { //on click video play ------------
    document.getElementById('myimg').style.display = 'none';
    document.getElementById('myVideo').style.display = 'block';
    document.getElementById('myVideo').play();
    }
</script>

Google map show a map using address on website

 <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
 var geocoder;
  var map;

  function codeAddress() {
   geocoder = new google.maps.Geocoder();
  
    var latlng = new google.maps.LatLng(33.449204, -112.074387);
   
    var mapOptions = {
     
      center: latlng,
          zoom: 12,
    mapTypeId: google.maps.MapTypeId.TERRAIN
        }
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
   
    var address = 'Indira Gandhi International Airport, New Delhi, Delhi, India';
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

     var lat=results[0].geometry.location.lat();
   
     var lng=results[0].geometry.location.lng();
   
     map.setCenter(new google.maps.LatLng(lat, lng));
   
     var marker = new google.maps.Marker({
       
            position: results[0].geometry.location,
            map: map,
            animation: google.maps.Animation.DROP,
           
        });
       
              var infowindow = new google.maps.InfoWindow();
            infowindow.setContent('<div class="mapinfo"> Indira Gandhi International Airport, New Delhi, Delhi, India</div>');
            infowindow.open(map, marker);     
           
            }

    });
   
   
    }


           
</script>
<body onload="codeAddress();">
 <div id="form2left">
        <div id="map-canvas" style="width: 100%; height: 100%;"></div>
      </div>
      </body>

Saturday 23 April 2016

Magento adding existing attribute to all attribute sets

<?php
require_once "app/Mage.php";
Mage::app();
$attSet = Mage::getModel('eav/entity_type')->getCollection()->addFieldToFilter('entity_type_code','catalog_product')->getFirstItem(); // This is because the you adding the attribute to catalog_products entity ( there is different entities in magento ex : catalog_category, order,invoice... etc )
    $attSetCollection = Mage::getModel('eav/entity_type')->load($attSet->getId())->getAttributeSetCollection(); // this is the attribute sets associated with this entity
    $attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
        ->setCodeFilter('attribute_code') //insert your attribute code here
        ->getFirstItem();
    $attCode = $attributeInfo->getAttributeCode();
    $attId = $attributeInfo->getId();
    foreach ($attSetCollection as $a)
    {
        $set = Mage::getModel('eav/entity_attribute_set')->load($a->getId());
        $setId = $set->getId();
        $group = Mage::getModel('eav/entity_attribute_group')->getCollection()->addFieldToFilter('attribute_set_id',$setId)->setOrder('attribute_group_id',"ASC")->getFirstItem();
        $groupId = $group->getId();
        $newItem = Mage::getModel('eav/entity_attribute');
        $newItem->setEntityTypeId($attSet->getId()) // catalog_product eav_entity_type id ( usually 10 )
                  ->setAttributeSetId($setId) // Attribute Set ID
                  ->setAttributeGroupId($groupId) // Attribute Group ID ( usually general or whatever based on the query i automate to get the first attribute group in each attribute set )
                  ->setAttributeId($attId) // Attribute ID that need to be added manually
                  ->setSortOrder(10) // Sort Order for the attribute in the tab form edit
                  ->save()
        ;
        echo "Attribute ".$attCode." Added to Attribute Set ".$set->getAttributeSetName()." in Attribute Group ".$group->getAttributeGroupName()."<br>\n";
    }

Wednesday 20 April 2016

How To Export and Import Categories in Magento

Step 1 of 4: Write the following code in export-category.php and place it to root directory. Run this file at browser http://www.yourdomain.com/export-category.php. It will generate a CSV file  Categories.csv (export all categories).


<?php
ini_set("memory_limit","10000M");
require_once "app/Mage.php";
umask(0);
Mage::app();
$category = Mage::getModel ( 'catalog/category' );
$tree = $category->getTreeModel ();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
if ($ids) {
 $string='';
 $heading = '"store","categories","cat_id","is_active","meta_title","meta_keywords","meta_description","include_in_menu","is_anchor","description",';
 foreach ($ids as $id){
  if($id>0)
  {
   $cate_cre = Mage::getModel('catalog/category');
   $cate_cre->load($id);
   $treeurl='';
   $cate_cre1=Mage::getModel('catalog/category')->load($id);
   $treeurl=$cate_cre->getName();
   if($cate_cre1->getParentId()>0)
   {
   for($i=0; ;$i++)
   {
   if($cate_cre1->getParentId()>0)
   {
   $abc=Mage::getModel('catalog/category')->load($cate_cre1->getParentId());
   $pCat=$abc->getName();
   if($abc->getId()>1){
   $treeurl=$pCat.'/'.$treeurl;
   }
   $cate_cre1=$abc;
   }
   else{
   break;
   }
   }
   }
   $store = "default";
   $string .='"'.$store.'","'.$treeurl.'","'.$id.'","'.$cate_cre->getIsActive().'","'.$cate_cre->getMetaTitle().'","'.$cate_cre->getMetaKeywords().'","'.$cate_cre-

>getMetaDescription().'","'.$cate_cre->getIncludeInMenu().'","'.$cate_cre->getIsAnchor().'","'.$cate_cre->getDescription().'"';
   $string.="\n";
  }
 }
 $csv_output = $heading ."\n".$string;
 $filename = "Categories";
 header("Content-type: application/vnd.ms-excel");
 header("Content-disposition: csv" . date("Y-m-d") . ".csv");
 header( "Content-disposition: filename=".$filename.".csv");
 print $csv_output;
}
?>

Step 2 of 4:  Import the categories :-
create config.xml  at app\code\local\Lky\Catalog\etc\config.xml
create Category.php at app\code\local\Lky\Catalog\Model\Convert\Adapter\Category.php
create Lky_All.xml  at  app\etc\modules

Code of config.xml :-
<?xml version="1.0"?>
<config>
  <global>
    <models>
      <catalog>
        <rewrite>
        <convert_adapter_category>Lky_Catalog_Model_Convert_Adapter_Category</convert_adapter_category>
    </rewrite>
   </catalog>
  </models>
 </global>
</config>

Code of Category.php :-

<?php
class Lky_Catalog_Model_Convert_Adapter_Category extends Mage_Eav_Model_Convert_Adapter_Entity
{
 protected $_categoryCache = array();
 protected $_stores;
 /**
 * Category display modes
 */
 protected $_displayModes = array( 'PRODUCTS', 'PAGE', 'PRODUCTS_AND_PAGE');

 public function parse()
 {
 $batchModel = Mage::getSingleton('dataflow/batch');
 $batchImportModel = $batchModel->getBatchImportModel();
 $importIds = $batchImportModel->getIdCollection();
 foreach ($importIds as $importId){
  $batchImportModel->load($importId);
  $importData = $batchImportModel->getBatchData();
  $this->saveRow($importData);
 }
 }
 /**
 * Save category (import)
 * @param array $importData
 * @throws Mage_Core_Exception
 * @return bool
 */
 public function saveRow(array $importData)
 {
 if (empty($importData['store'])) {
   if (!is_null($this->getBatchParams('store'))) {
   $store = $this->getStoreById($this->getBatchParams('store'));
   } else {
   $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
   Mage::throwException($message);
   }
 }else{
  $store = $this->getStoreByCode($importData['store']);
 }
 if ($store === false){
  $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
  Mage::throwException($message);
 }
 $rootId = $store->getRootCategoryId();
  if (!$rootId) {
  return array();
  }
 $rootPath = '1/'.$rootId;
  if (empty($this->_categoryCache[$store->getId()])) {
  $collection = Mage::getModel('catalog/category')->getCollection()
              ->setStore($store)
              ->addAttributeToSelect('name');
 $collection->getSelect()->where("path like '".$rootPath."/%'");
 foreach ($collection as $cat) {
  $pathArr = explode('/', $cat->getPath());
  $namePath = '';
  for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) {
  $name = $collection->getItemById($pathArr[$i])->getName();
  $namePath .= (empty($namePath) ? '' : '/').trim($name);
  }
  $cat->setNamePath($namePath);
 }
  $cache = array();
  foreach ($collection as $cat) {
  $cache[strtolower($cat->getNamePath())] = $cat;
  $cat->unsNamePath();
  }
  $this->_categoryCache[$store->getId()] = $cache;
  }
  $cache =& $this->_categoryCache[$store->getId()];
  $importData['categories'] = preg_replace('#\s*/\s*#', '/', trim($importData['categories']));
  if (!empty($cache[$importData['categories']])) {
  return true;
  }
  $path = $rootPath;
  $namePath = '';
  $i = 1;
 $categories = explode('/', $importData['categories']);
 /*$IsActive = $importData['IsActive'];*/
 $IsActive = $importData['is_active'];
 $IsAnchor =$importData['is_anchor'];
 $Description =$importData['description'];
 $IncludeInMenu=$importData['include_in_menu'];
 $MetaTitle=$importData['meta_title'];
 $MetaKeywords=$importData['meta_keywords'];
 $MetaDescription=$importData['meta_description'];
 $Image=$importData['image'];
 $URlkey=$importData['url_key'];
  foreach ($categories as $catName) {
  $namePath .= (empty($namePath) ? '' : '/').strtolower($catName);
  if (empty($cache[$namePath])) {
  $dispMode = $this->_displayModes[2];
    $cat = Mage::getModel('catalog/category')
    ->setStoreId($store->getId())
    ->setPath($path)
    ->setName($catName)
    ->setIsActive($IsActive)
    ->setIsAnchor($IsAnchor)
    ->setDisplayMode($dispMode)->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $cat->setIncludeInMenu($IncludeInMenu);
   $cat->setDescription($Description);
   $cat->setMetaTitle($MetaTitle).
    $cat->setMetaKeywords($MetaKeywords);
    $cat->setMetaDescription($MetaDescription);
    $cat->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_title']=$MetaTitle;
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_description']=$MetaDescription;
   $data['url_key']= $URlkey;
   $cat->addData($data);
   $cat->save();
  $cache[$namePath] = $cat;
  }
  $catId = $cache[$namePath]->getId();
  $path .= '/'.$catId;
  $i++;
  }
  return true;
 }

 /**
 * Retrieve store object by code
 *
 * @param string $store
 * @return Mage_Core_Model_Store
 */
 public function getStoreByCode($store)
 {
  $this->_initStores();
  if (isset($this->_stores[$store])) {
  return $this->_stores[$store];
  }
  return false;
 }

 /**
 * Init stores
 *
 * @param none
 * @return void
 */
 protected function _initStores ()
 {
  if (is_null($this->_stores)) {
  $this->_stores = Mage::app()->getStores(true, true);
  foreach ($this->_stores as $code => $store) {
  $this->_storesIdCode[$store->getId()] = $code;
  }
  }
 }
}

?>

Code of Lky_All.xml

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

Step 3 of 4 : create dataflow advanced profile at admin > system > Import/Export > Dataflow - Advanced Profile and give the Profile Name is 'category import'.

place the following code to its Actions xml box :-

<action type="dataflow/convert_adapter_io" method="load">
     <var name="type">file</var>
     <var name="path">var/import</var>
     <var name="filename"><![CDATA[Categories.csv]]></var>
     <var name="format"><![CDATA[csv]]></var>
    </action>
    <action type="dataflow/convert_parser_csv" method="parse">
     <var name="delimiter"><![CDATA[,]]></var>
     <var name="enclose"><![CDATA["]]></var>
     <var name="fieldnames">true</var>
     <var name="store"><![CDATA[0]]></var>
     <var name="number_of_records">1</var>
     <var name="decimal_separator"><![CDATA[.]]></var>
     <var name="adapter">catalog/convert_adapter_category</var>
     <var name="method">parse</var>
    </action>

Step 4:  Put Categories.csv into var/import/ and removed cat_id colums from csv.
             remove first two rows.
            remove all Default Category/ from categories colunn in Categories.csv
           Now to Run Profile admin > system > Import/Export > Dataflow-Advanced Profile
           run 'category import' profile  from Run Profile > click 'Run Profile in Popup'
           import of category now start and automatically created category.

Wednesday 13 April 2016

drawing signature using canvas in jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script>
    var mousePressed = false;
var lastX, lastY;
var ctx;

function InitThis() {
    ctx = document.getElementById('myCanvas').getContext("2d");

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        mousePressed = false;
    });
        $('#myCanvas').mouseleave(function (e) {
        mousePressed = false;
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = 'black';
        ctx.lineWidth = '3';
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x; lastY = y;
}
   
function clearArea() {
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function imgcreate() {
//to append image in body
var can = document.getElementById('myCanvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
$("#imgct").html(img);
//image upload
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
     $('#sign').val(Pic);
    }
</script>

<body onLoad="InitThis();">
<form class="" action="form-submit.php" method="post">
<canvas id="myCanvas" width="500" height="200" style="border:2px solid black"></canvas>
<br /><br />
        <button onClick="javascript:clearArea();return false;">Refresh</button>
<input type="submit" value="Save" name="save" onMouseOver="return imgcreate();">
</form>
<div id="imgct"></div>
</body>
For upoad image to server create a php file with "form-submit.php" name. And use below code to save createed image :-
<?php
file_put_contents('images/test.png', base64_decode(substr($_POST['sign'], strpos($_POST['sign'], ",")+1)));
?>
After submit form image will be saved in images folder.

Monday 11 April 2016

Magento how to add new category attribute

Just copy paste the below code in header.phtml and run your magento once, your attribute will be created and you can see in backend under manage category. After you are done remove this code again.

<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

//Add selectbox attribure
$setup->addAttribute('catalog_category', 'add_slider', array(
    'group'         => 'Show home on slider',
    'input'         => 'select',
    'type'          => 'varchar',
    'label'         => 'Status',
    'option'        => array ('value' => array('optionone'=>array(0=>'Enable'),'optiontwo'=>array(0=>'Disable')) ),
    'backend'        => 'eav/entity_attribute_backend_array',
    'visible'       => 1,
    'required'      => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

//Add input type text attribure.
$setup->addAttribute(Mage_Catalog_Model_Category::ENTITY, 'slider_title', array(
    'group'         => 'Show home on slider',
    'input'         => 'text',
    'type'          => 'text',
    'label'         => 'Slider title',
    'backend'       => '',
    'visible'       => true,
    'required'      => false,
    'visible_on_front' => true,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
));

//Add image attribure
$setup->addAttribute('catalog_category', 'slider_image', array(
    'group'         => 'Show home on slider',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Slider image',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
)); ?>


To get attributes value paste following code in product list page (list.phtml) and you will get attribute value.

 <?php  $currentcategory = Mage::registry('current_category');
    $catId =  $currentcategory->getId();
    $current_category = Mage::getModel('catalog/category')->load($catId);
    $mediaUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."catalog/category/";
    echo $staus =  $current_category->getAddSlider()."<br/>";
    echo $title =  $current_category->getSliderTitle()."<br/>";
    echo $image =  $mediaUrl.$current_category->getSliderImage()."<br/>";
     ?>

Friday 8 April 2016

magento how to get sample file of downloadable products

 <?php $_myprodsamples = Mage::getModel('downloadable/sample');
 $download_fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."downloadable/files/samples";
$_mySampleCollection = $_myprodsamples->getCollection()
                   ->addProductToFilter($_product->getId())
                   ->addTitleToResult($_product->getStoreId());
?>



<?php foreach ($_mySampleCollection as $_sample1){
  //echo $_samplelink = $this->getUrl('downloadable/download/linkSample/link_id/'.$_sample ->getId());
   echo $_sample1->getSampleType(); //get file type
  echo $download_fileUrl.$_sample1->getSampleFile(); //Get file with url
  echo $_sample1->getSampleUrl();//get url if exist
   echo $_sample1->getTitle();
   print_r($_sample1); }?>

How to delete folder with contents in php

<?php

 function deletedir($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? deletedir("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }  
  deletedir("filePath");
  deletedir("../file");

?>

Friday 1 April 2016

Select All checkboxes using jQuery

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script>
var noc = jQuery.noConflict();
noc(document).ready(function () {
    noc("#ckbCheckAll").click(function () {
        noc(".checkBoxClass").prop('checked', noc(this).prop('checked'));
    });
     });
</script>

<input type="checkbox" id="ckbCheckAll" />
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>

simple paging in php

<?php
$vendor_count_data="SELECT COUNT(id) FROM tableName";
$vendor_data="SELECT * FROM tableName";

$pnn = "?pn=";
$sql = $vendor_count_data;
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$rows = $row[0]; // This is the number of results we want displayed per page
$page_rows = 2; // This tells us the page number of our last page
$last = ceil($rows/$page_rows); // This makes sure $last cannot be less than 1
if($last < 1){ $last = 1; } // Establish the $pagenum variable
$pagenum = 1; // Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){ $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']); }
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) { $pagenum = 1; } else if ($pagenum > $last) { $pagenum = $last; }
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
//$sql = "SELECT * FROM location_city WHERE status ='1' ORDER BY id DESC $limit";
$sql =$vendor_data." ".$limit;
$query = mysql_query($sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "$rows";
/* Showing 1 to 10 of 11 entries CUSTOM CODE */
//$textline2 = ($pagenum*10)." to ". $last;

if($pagenum==1)
{
$row_start=$pagenum;
}
else
{
$row_start=($page_rows*($pagenum-1))+1;
}
if(($pagenum*$page_rows)<$rows) {
$textline2 = $row_start." to ". ($pagenum*$page_rows);
}else
{
$textline2 = $row_start." to ". $rows;
}

$paginationCtrls = '';
if($last != 1){
$previous = $pagenum - 1;
if($pagenum!=1)
 {
 $paginationCtrls .= "<li><a href='".$pnn."1'>First</a></li><li><a href='".$pnn.$previous."'>Previous</a></li>";
 }
 
for($i = $pagenum-4; $i < $pagenum; $i++){ if($i > 0){ $paginationCtrls .= "<li><a href='".$pnn.$i."'>".$i."</a></li>"; /*}*/ } }
$paginationCtrls .= '<li><a href="javascript:void(0)" class="active">'.$pagenum.'</a></li>';
for($i = $pagenum+1; $i <= $last; $i++){ $paginationCtrls .= "<li><a href='".$pnn.$i."'>".$i."</a></li>";
if($i >= $pagenum+4){ break; } }
$next = $pagenum + 1;
if($last!=$pagenum)
{
$paginationCtrls .= "<li><a href='".$pnn.$next."'>Next</a></li> <li><a href='".$pnn.$last."'>Last</a></li>";
}

 } $list = '';

$i=$row_start;

while($row = mysql_fetch_array($query, MYSQL_ASSOC))
{ ?>
<p><?php echo $i; ?></p>
<p><?php echo $row['id']; ?> </p>

<?php $i++; } ?>
<?php //----show paging here------- ?>
<div class="pages-list">
<ul>
<?php echo $paginationCtrls; ?> 
</ul>
</div>
</div>

Friday 18 March 2016

how to play youtube video in popup window using jquery

<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<span onclick="playvideo('1');player1.playVideo();" class="yt-link"><h1>Play</h1></span>
<div style="display: none;" id="pop_1" class="video-popup">
 <span onclick="closevideo('1');player1.pauseVideo();" class="closed">X</span>
 <iframe width="800" height="600" frameborder="0" allowfullscreen="true" onload="player1=new YT.Player(this)" src="http://www.youtube.com/embed/8HQIKJBUsQk?rel=0&amp;enablejsapi=1" id="if_"></iframe>
 </div>


<span onclick="playvideo('2');player2.playVideo();" class="yt-link"><h1>Play</h1></span>
<div style="display:none;" id="pop_2" class="video-popup">
 <span onclick="closevideo('2');player2.pauseVideo();" class="closed">X</span>
 <iframe width="800" height="600" frameborder="0" allowfullscreen="true" onload="player2=new YT.Player(this)" src="http://www.youtube.com/embed/X71R64AdoOo?rel=0&amp;enablejsapi=1" id="if_"></iframe>
 </div>

 <span onclick="playvideo('3');player3.playVideo();" class="yt-link"><h1>Play</h1></span>
  <div style="display:none;" id="pop_3" class="video-popup">
 <span onclick="closevideo('3');player3.pauseVideo();" class="closed">X</span>
 <iframe width="800" height="600" frameborder="0" allowfullscreen="true" onload="player3=new YT.Player(this)" src="http://www.youtube.com/embed/BOCvHWoqssI?rel=0&amp;enablejsapi=1" id="if_"></iframe>
 </div>

 <span onclick="playvideo('4');player4.playVideo();" class="yt-link"><h1>Play</h1></span>
 <div style="display:none;" id="pop_4" class="video-popup">
 <span onclick="closevideo('4');player4.pauseVideo();" class="closed">X</span>
 <iframe width="800" height="600" frameborder="0" allowfullscreen="true" onload="player4=new YT.Player(this)" src="http://www.youtube.com/embed/qBLN-sOL6eU?rel=0&amp;enablejsapi=1" id="if_"></iframe>
 </div>                     
 <script>
var noc = jQuery.noConflict();
function playvideo(ytid) {
noc("#pop_"+ytid).show();
}
function closevideo(ids) {
noc("#pop_"+ids).hide();
}
</script>

  

Thursday 11 February 2016

Magento Add custom image attribute to category


 Just copy paste the below code in header.phtml and run your magento once, your attribute will be created and you can see in backend under manage category. After you are done remove this code again.
 
<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('catalog_category', 'sliderimage2', array(
    'group'         => 'General',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Slider Image 2',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
)); ?>

Tuesday 2 February 2016

How to change the Magento Email Templates

You’ll probably know by now that the transactional email templates in Magento are a bit, with respect, “naff”. To edit through the admin will take forever and a day so here’s a couple of useful solutions to help make things easier.


Locate the email templates.
The Magento email templates are located in (note: “en_US” may change depending on language).
magento\app\locale\en_US\template\email\account_new.html”:
magento\app\locale\en_US\template\email\admin_password_new.html”:
magento\app\locale\en_US\template\email\sales\newsletter_subscr_confirm.html”:
magento\app\locale\en_US\template\email\sales\order_creditmemo.html”:
magento\app\locale\en_US\template\email\sales\order_creditmemo.html”:
magento\app\locale\en_US\template\email\sales\order_invoice.html”:
magento\app\locale\en_US\template\email\sales\order_invoice.html”:
magento\app\locale\en_US\template\email\sales\order_new.html”:
magento\app\locale\en_US\template\email\sales\order_new.html”:
magento\app\locale\en_US\template\email\sales\order_shipment.html”:
magento\app\locale\en_US\template\email\sales\order_shipment.html”:
magento\app\locale\en_US\template\email\sales\order_update.html”:
magento\app\locale\en_US\template\email\password_new.html”:
magento\app\locale\en_US\template\email\wishlist_share.html”:

Magento add CMS Static Block underneath categories in left sidebar

Paste below xml code in custom design part  for call static block after left navigation.

 <reference name="left">
<block type="cms/block" name="book_left_block" after="catalog.leftnav">
<action method="setBlockId"><block_id>book_left_block</block_id></action>
</block>
</reference>

For remove left navigation from left sidebar.
 <reference name="left">
<block type="cms/block" name="book_left_block" after="catalog.leftnav">
<action method="setBlockId"><block_id>book_left_block</block_id></action>
</block>
<remove name="catalog.leftnav" />
</reference>

Tuesday 12 January 2016

How to remove public and index.php from URL in laravel

1.) First copy all files of public folder and paste in root directry.

2.) open the index file

set path on line no. 21 require __DIR__.'/bootstrap/autoload.php';
and line no. 35   $app = require_once __DIR__.'/bootstrap/app.php';
 
3.) Open .htaccess file and paste following code.

Options -MultiViews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]