Wednesday, 19 October 2016

magento 2 comment

cd /var/www/html && php bin/magento setup:upgrade && php bin/magento setup:static-content:deploy && chmod -R 0777 *

Thursday, 22 September 2016

How to get cart item remove or empty (truncate) in magento 2

Company name :- Sbr
Module name :- Checkout
File path :- /app/code/Sbr/Checkout/etc
============= File name events.xml =====================

<?xml version="1.0"?>
<!--
/**
 * @author     SB , SBR
 * @package    Sbr_Checkout
 * @copyright  Copyright (c) 2015 Sbr Limited (http://www.Sbr.co.nz)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="beforecart"
                  instance="Sbr\Checkout\Observer\BeforeCart"/>
    </event>
</config>

=================================================

============= File name module.xml =====================
<?xml version="1.0"?>
<!--
/**
 * @author     SB, Sbr
 * @package  
 * @copyright  Copyright (c) 2015 Sbr
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Sbr_Checkout" setup_version="2.0.4">      
    </module>
</config>


======================================================
============= File name BeforeCart.php =====================
File path :- /app/code/Sbr/Checkout/Observer

<?php

namespace Sbr\Checkout\Observer;
/*
ini_set("display_errors", "On");
error_reporting(E_ALL);
*/
use Magento\Framework\Event\ObserverInterface;

class BeforeCart implements ObserverInterface {
   
    protected $cart;
   
    public function __construct(
        \Magento\Checkout\Model\Cart $cart
    ) {
         $this->cart = $cart;
     
    }
   
    public function execute(\Magento\Framework\Event\Observer $observer) {

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager   =   $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore   =   $storeManager->getStore();
$currentStore_id = $currentStore->getId();
if($currentStore_id==1):
$count=count($this->cart->getItems());
if($count>=1){
foreach($this->cart->getItems() as $_item){
$sku=trim($_item['sku']);
if(($sku=='basic1')||($sku=='starter')||($sku=='professional')||($sku=='premium')){
$this->cart->truncate();
}
}
}

endif;
    }

}

=================================================================




==============File name registration.php ========================
File path:- app/code/Sbr/Checkout
<?php
 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Sbr_Checkout',
    __DIR__
);

====================================

How to get customer data from email id in magento 2

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$customer_email=$_REQUEST['list'];
///echo $customer_email;exit;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();


    $url = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
    $state = $objectManager->get('\Magento\Framework\App\State');
    $state->setAreaCode('frontend');
    $websiteId = $storeManager->getWebsite()->getWebsiteId();
    // Get Store ID
    $store = $storeManager->getStore();
    $storeId = $store->getStoreId();
    $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
    $customer=$customerFactory->create();
    $customer->setWebsiteId($websiteId);
    $customer->loadByEmail($customer_email);// load customer by email address
    //echo $customer->getEntityId();
    //$customer->load('1');// load customer by email address
    $data= $customer->getData();
$customer_id=$data['entity_id'];

Thursday, 15 September 2016

How to get Category Id of current product in magento

$categoryIds = $_product->getCategoryIds();      
            if(count($categoryIds) ){
                $firstCategoryId = $categoryIds[0];
                $_category = Mage::getModel('catalog/category')->load($firstCategoryId);

                echo $_category->getName();
               echo $_category->getId();
            }

Monday, 12 September 2016

Magento Select Query

$connectionWrite = Mage::getSingleton('core/resource')->getConnection('core_read');
$resource = Mage::getSingleton('core/resource');
$tableName = $resource->getTableName('marketplace_product');
$query = 'SELECT userid FROM ' . $tableName . ' WHERE mageproductid = '.(int)$product_Id ;

$userid = $connectionWrite->fetchOne($query); 

Thursday, 28 July 2016

mahemto cart use on set description

 ===Set Description===================================
 app/code/core/Mage/Sales/Model/Quote.php
 public function addProductAdvanced(
 after this coding :-
 $items[] = $item;
 $item->setDescription($_customValue);

 =========================================
 app/design/frontend/rwd/nassaunationalcable/template/checkout/cart/item/default.phtml
 $_item->getDescription();

how to remove customer account dashboard links


Step 1: Go to ( yourPackage/YourTemplate/customer/account/navigation.phtml )

Step 2: Replace the below line

<?php $count = count($links); ?>
        **With**
<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
      unset($_links['account']); /* Account Info */    
      unset($_links['account_edit']); /* Account Info */           
      unset($_links['tags']); /* My Tags */
      unset($_links['invitations']); /* My Invitations */
      unset($_links['reviews']);  /* Reviews */
      unset($_links['wishlist']); /* Wishlist */
      unset($_links['newsletter']); /* Newsletter */
      unset($_links['orders']); /* My Orders */
      unset($_links['address_book']); /* Address */
      unset($_links['enterprise_customerbalance']); /* Store Credit */
      unset($_links['OAuth Customer Tokens']); /* My Applications */
      unset($_links['enterprise_reward']); /* Reward Points */
      unset($_links['giftregistry']); /* Gift Registry */
      unset($_links['downloadable_products']); /* My Downloadable Products */
      unset($_links['recurring_profiles']); /* Recurring Profiles */
      unset($_links['billing_agreements']); /* Billing Agreements */
      unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */
?>

Wednesday, 27 July 2016

how to get selected drop down attribute value disply on in frontend?

$_product =Mage::getModel('catalog/product')->load($_product_ID);
                            echo $_product_s->getLength();
                            ======== OR ==========
                            echo  $_product_s->getAttributeText('length');
                            echo $_product->getResource()->getAttribute('length')
                             ->getFrontend()->getValue($_product);

Monday, 25 July 2016

How to call store address on static block

<p><span class="address-heading">{{config path="general/store_information/name"}}</span>
{{config path="general/store_information/address"}}<br />
<br /> {{config path="trans_email/ident_general/email"}}<br />
{{config path="general/store_information/phone"}}</p>

Friday, 22 July 2016

magento 2 base url and media url

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager   =   $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
    $currentStore   =   $storeManager->getStore();
/*********** Base url******/
    $baseUrl      =   $currentStore->getBaseUrl();


/*********** mediaUrl url******/
 $mediaUrl      =   $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

Tuesday, 19 July 2016

magento cart url

$params = array(
                               
                                'product'=> $_product->getId(),
                                Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => Mage::helper('core/url')->getEncodedUrl(),
                                'form_key'=>Mage::getSingleton('core/session')->getFormKey(),'_secure'=>false
                                );
                                $addToCartUrl= $this->getUrl("checkout/cart/addToCartFromList/", $params ).'?super_attribute['.$super_a_id.']='.$option['value'];
                                ?>

how to get categories ids calection by product on magento

$_product->getCategoryIds();

Monday, 11 July 2016

how to cutom mail send by load templated

/app/code/local/artis/Testimonial/etc/config.xml

Add this code:-
<global>
        <template>
        <email>
        <contacts_email_configuration_select_template_post translate="label" module="testimonial">
            <label>Custom Email Template After Post Quote Request</label>
            <file>email_template_after_post_request.html</file>
            <type>html</type>
        </contacts_email_configuration_select_template_post >
        </email>
    </template>
    </global>
   
Careted this file on this path:-
app/locale/en_US/template/email/email_template_after_post_request.html

<!--@subject Testimonial submission! @-->

{{template config_path="design/email/header"}}
{{inlinecss file="email-inline.css"}}

<table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td class="action-content">
            <h1>Dear Admin,</h1>
        </td>
    </tr>
    <tr>
        <td class="action-content">
            <p>Name: {{var name }}</p>
        </td>
    </tr>
    <tr>
        <td class="action-content">
            <p>Company: {{var company }}</p>
        </td>
    </tr>
    <tr>
        <td class="action-content">
            <p>Email: {{var email }}</p>
        </td>
    </tr>
    <tr>
        <td class="action-content">
            <p>Telephone {{var telephone }}</p>
        </td>
    </tr>
        <tr>
        <td class="action-content">
            <p>Wire / Cable Description: {{var description }}</p>
        </td>
    </tr>
            <tr>
        <td class="action-content">
            <p>Length: {{var length }}</p>
        </td>
    </tr>
                <tr>
        <td class="action-content">
            <p>Date Required: {{var drequired }}</p>
        </td>
    </tr>
    <tr>
        <td class="action-content">
            <p>Additional Questions / Comments: {{var acomments}}</p>
        </td>
    </tr>
</table>       

{{template config_path="design/email/footer"}}



/app/code/local/Artis/Contacts/controllers/IndexController.php
==================
 public function quoterequestAction()
    {
        $post = $this->getRequest()->getPost();
        if ( $post ) {
           
            $emailTemplate = Mage::getModel('core/email_template')->loadDefault('contacts_email_configuration_select_template_post');
            $emailTemplateVariables = array();
            $emailTemplateVariables = array();
            $emailTemplateVariables['name'] = $post['name'];
            $emailTemplateVariables['companyname'] = $post['companyname'];
            $emailTemplateVariables['email'] = $post['email'];
            $emailTemplateVariables['telephone'] = $post['telephone'];
            $emailTemplateVariables['description'] = $post['description'];
            $emailTemplateVariables['length'] = $post['length'];
            $emailTemplateVariables['drequired'] = $post['drequired'];
            $emailTemplateVariables['acomments'] = $post['acomments'];
            //print_r($emailTemplateVariables);exit;
           
           
          
            $emailTemplateVariables['customer_email'] = $post['email'];
           
            $emailTemplate->getProcessedTemplate($emailTemplateVariables);
           
            $emailTemplate->setSenderName($post['name']);
            $emailTemplate->setSenderEmail($post['email']);
           
            $recipientName = 'test';
            $recipientEmail = 'artis.test70@gmail.com';
           
            $emailTemplate->send($recipientEmail,$recipientName,$emailTemplateVariables);
        }
    }
==========================

============ Form page:- ==================================
<div class="col-md-9">
<div class="quest-quote-outer">
    <h3>Quote Request</h3>
    <p><strong>Can't find what you are looking for or just want to request a quote?</strong> Fill out the form below or give us a call at (516) 606-6537 or send us an email at <strong><a href="mailto:sales@nassaunationalcable.com">sales@nassaunationalcable.com</a></strong></p>
    <h4>We guarantee same day response!</h4>
    <p>
        Phone: (516) 606-6537</br>E-Fax: (480) 287-9579</br>Fax: (516) 482-6438</br>Email: <a href="mailto:sales@nassaunationalcable.com">sales@nassaunationalcable.com</a>
    </p>
        <form method="post" id="qutote-form" name="qutote-form" class="qutote-form" action="<?php echo Mage::getUrl(); ?>contacts/index/quoterequest/">
        <div class="qutote-form-row1">
            <h3 class="legend">Contact Information</h3>
            <ul class="form-list">
                <li class="fields">
                    <div class="field name">
                        <label  class="required">Name:</label>           
                        <div class="input-box">
                            <input type="text" name="name" id="name" class="input-text required-entry" style="" value="" />                                       
                        </div>
                    </div>
                    <div class="field company">
                        <label for="field_15">Company:</label>               
                        <div class="input-box">
                            <input type="text" name="companyname" id="companyname" class="input-text" style="" value="" />                                                   
                        </div>
                    </div>
                </li>
                <li class="fields">
                    <div class="field email">
                        <label class="required">Email:</label>                   
                        <div class="input-box">
                            <input type="text" name="email" id="email" class="input-text required-entry validate-email" style="" value="" />                   
                        </div>
                    </div>
                    <div class="field webforms-fields-telephone">
                        <label>Telephone:</label>           
                        <div class="input-box">
                            <input type="text" name="telephone" id="telephone" class="input-text" style="" value="" />                                           
                        </div>
                    </div>
                </li>
            </ul>
        </div>
        <div class="qutote-form-row2">
            <h3 class="legend">Contact Information</h3>
            <ul class="form-list">
                <li class="wide">
                    <label  class="required">Wire / Cable Description:</label>
                    <div class="input-box">
                        <textarea name="description" id="description" class="input-text required-entry wire-request-details" style=""></textarea>                   
                    </div>
                </li>
                <li class="fields">
                    <div class="field length">
            <label class="required">Length:</label>
            <div class="input-box">
                        <input type="text" name="length" id="length" class="input-text required-entry" style="" value="" />
            </div>
                    </div>
                    <div class="field date-needed">
            <label >Date Required:</label>
            <div class="input-box">
                        <input type="text" name="drequired" id="drequired" class="input-text " style="" value="" />
            </div>
                    </div>
                </li>
                <li class="wide">
            <div class=" webforms-fields-comments">
                        <label>Additional Questions / Comments:</label>           
                        <div class="input-box">
                            <textarea name="acomments" id="acomments" class="input-text" style=""></textarea>               
                        </div>
                    </div>
        </li>
            </ul>
        </div>
        <div class="buttons-set">
            <p class="required">* Required Fields</p>
            <input type="submit" value="submit" class="r-submit">
        </div>
       
    </form>
</div>
</div>




<div class="col-md-3">
<?php echo  $this->getLayout()->createBlock('cms/block')->setBlockId('right-block')->toHtml();?>
</div>


<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('qutote-form', true);
//]]>
</script>
===========================================

Sunday, 10 July 2016

how to enable the product review form anywhere

catalog.xml enable it with:

<block type="review/form" name="product.info.review_form" as="review_form" template="review/form.phtml"/>
and in your template:

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

Saturday, 9 July 2016

how to displaying review block (with ratings) on custom page in magento

<?php
$_product = $_item->getProduct(); //get the product in cart
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')
->setStoreId($storeId)
->load($_product->getId());

if ($summaryData['rating_summary']):?>
<div class="ratings">
<div class="rating-box">
<div class="rating" style="width:<?php echo $summaryData['rating_summary']; ?>%"></div>
</div>
</div>
<?php endif; ?>

Thursday, 7 July 2016

how to remove product wishlist remove custom page on magento

Customer account controllers path :-
/app/code/local/Companyname/Customer/controllers

public function wishlistRemoveAction(){
        $proid= $_REQUEST['proid'];
        $customerid= $_REQUEST['customerid'];
       
        $itemCollection = Mage::getModel('wishlist/item')->getCollection()->addCustomerIdFilter($customerid);
        foreach($itemCollection as $item) {
        if($item->getProductId()==$proid)
            $item->delete();
        }
       
    }

 List page :-

<input type="hidden" id="remove_url" value="<?php echo $this->getUrl();?>customer/account/wishlistRemove"/>

<a href="javascript:void(0)" class="link-wishlist click-remove" data-proid="<?php echo $_product->getId(); ?>" data-customerid="<?php echo $customerId; ?>">
                                <i class="fa fa-star-o"></i>
                            </a>

JQuery :-


jQuery('.click-remove').click(function() {
    var base_url=jQuery.trim(jQuery("#remove_url").val());
    var pro_Id=jQuery(this).data('proid');
    var customerid=jQuery(this).data('customerid');
    //alert(base_url);
    jQuery.ajax({
           url: base_url,
           type:  'post',
           data:({'proid':pro_Id,'customerid':customerid}),
           success: function(msg){
        location.reload();
           }
       });
      
    });

Monday, 4 July 2016

category attributes select type in magento

require_once('app/Mage.php');
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$installer = new Mage_Sales_Model_Mysql4_Setup;
$attribute = array(
'type' => 'int',
'label'=> 'Is Embroidery Country Ribbon',
'input' => 'select',
'source' => 'eav/entity_attribute_source_boolean',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => 0,
'group' => "General Information"
);
$installer->addAttribute('catalog_category', 'isembroiderycribbon', $attribute);
$installer->endSetup();

Tuesday, 28 June 2016

how to sort multi-dimensional array by value In PHP

$users =Array(  [0] =>
        Array (
             [username] => a
              [name] => Andrei Zmievski
        )

        [1] => Array (
            [username] => dotjay
            [name] => Jon Gibbins
        )

        [2] => Array  (
              [username] => shiflett
              [name] => Chris Shiflett
        )
    )


<?php
$names = array();
foreach ($users as $user) {
$names[] = $user['name'];}
array_multisort($names, SORT_ASC, $users);


?>

============================================

$orders =Array
(
    [item-1] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )

    [item-2] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [item-3] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )
)

usort($orders, 'sort_by_order ');
function sort_by_order ($a, $b)
{
    return $a['order'] - $b['order'];
}
print_r($orders)

Array
(
    [0] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )

    [1] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [2] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )
)

how to sort Multi-Dimensional Array By Value In PHP

$users =Array(  [0] =>
        Array (
             [username] => a
              [name] => Andrei Zmievski
        )

        [1] => Array (
            [username] => dotjay
            [name] => Jon Gibbins
        )

        [2] => Array  (
              [username] => shiflett
              [name] => Chris Shiflett
        )
    )


<?php
$names = array();
foreach ($users as $user) {
$names[] = $user['name'];}
array_multisort($names, SORT_ASC, $users);


?>

============================================

$orders =Array
(
    [item-1] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )

    [item-2] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [item-3] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )
)

usort($orders, 'sort_by_order ');
function sort_by_order ($a, $b)
{
    return $a['order'] - $b['order'];
}
print_r($orders)

Array
(
    [0] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )

    [1] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [2] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )
)

Thursday, 23 June 2016

how to category load by category id Magento 2

$objectManager   = \Magento\Framework\App\ObjectManager::getInstance();

$category = $objectManager->create('Magento\Catalog\Model\Category')->load($_cat->getId());

magento 2 Media url

$mediaUrl        = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

how to get current category Id on Magento 2

<?php
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
    echo $category->getId();
    echo $category->getName();
?>

select query Magento 2

<?php
                        $post_categroy='';
                        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
                        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
                        $connection = $resource->getConnection();
                        $tableName = $resource->getTableName('magefan_blog_post_category');
                        $sql = "SELECT category_id FROM ".$tableName." WHERE post_id=".$_post->getId();
                        $result = $connection->fetchOne($sql);
                        if(count($result)>0):
                            $tableName2 = $resource->getTableName('magefan_blog_category');
                            $post_catid     =   $result[0];
                            if($post_catid!=''){
                                $sql2 = "SELECT title FROM ".$tableName2." WHERE category_id=".$post_catid;
                                $post_categroy = $connection->fetchOne($sql2);
                               
                            }
                           
                        endif;
                    ?>

Thursday, 9 June 2016

Friday, 3 June 2016

remember me (id-password) functionality on magento login page.

Magento\app\code\core\Mage\Customer\controllers\AccountController.php

Step: 2 Find following function.

protected function _loginPostRedirect()



Step: 3 Replace with following function code.

protected function _loginPostRedirect()
{

        $session = $this->_getSession();

        if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl())
        {

               // Set default URL to redirect customer to

               $session->setBeforeAuthUrl(Mage::helper('customer')->getAccountUrl());

             // Redirect customer to the last page visited after logging in

             if ($session->isLoggedIn())
             {
                 if (!Mage::getStoreConfigFlag('customer/startup/redirect_dashboard'))
                 {
                       $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
                       if ($referer)
                       {
                                 $referer = Mage::helper('core')->urlDecode($referer);

                                 if ($this->_isUrlInternal($referer))
                                 {
                                       $session->setBeforeAuthUrl($referer);
                                 }
                        }
                }
                else if ($session->getAfterAuthUrl())
                {
                        $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
                }
            }
            else
            {
                $session->setBeforeAuthUrl(Mage::helper('customer')->getLoginUrl());
            }

       }
       else if ($session->getBeforeAuthUrl() == Mage::helper('customer')->getLogoutUrl())
       {
             $session->setBeforeAuthUrl(Mage::helper('customer')->getDashboardUrl());
       }
       else
       {
             if (!$session->getAfterAuthUrl())
             {
                  $session->setAfterAuthUrl($session->getBeforeAuthUrl());
             }

             if ($session->isLoggedIn())
             {
                  $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
             }
       }

       if ($this->getRequest()->isPost())
       {

             $login = $this->getRequest()->getPost('login');
             $rememberme = $this->getRequest()->getPost('rememberme');

             try
             {

                  $cookie = Mage::getModel('core/cookie');

                  if (!empty($login['username']) && !empty($login['password']) && !empty($rememberme))
                  {
                        $cookie->set('user_name', $login['username']);
                        $cookie->set('pass_user_name', $login['password']);
                        $cookie->set('rememberme', 1);
                  }
                  else if (!empty($login['username']) && !empty($login['password']) && empty($rememberme))
                  {
                        $cookie->delete('user_name');
                        $cookie->delete('pass_user_name');
                        $cookie->delete('rememberme');
                  }
             }
             catch (Exception $e)
             {
             }
       }
       $this->_redirectUrl($session->getBeforeAuthUrl(true));
}


Step: 4 Find following file (login page functionality).

Magento\app\design\frontend\default\[your theme]\template\customer\form\login.phtml

Step: 5 Add following code top of login.phtml.


<?php

          $cooki = Mage::getModel('core/cookie');

          $cookie_user_name = $cooki->get('user_name');

          $cookie_user_password = $cooki->get('pass_user_name');

          $rememberme = $cooki->get('rememberme');

?>


Step: 6 Find following code in login.phtml (user id textbox).

<input type="text" name="login[username]" value="<?php echo $this->escapeHtml($this->getUsername()) ?>" id="email" class="input-text required-entry validate-email" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Email Address')) ?>" />

And replace with the following code. The code define the user id of user if that user select remember me option.

<input name="login[username]" value="<?php if($cookie_user_name !=''){ echo $cookie_user_name;}else{ echo $this->htmlEscape($this->getUsername()); } ?>" title="<?php echo $this->__('Email Address') ?>" id="email" class="input-text required-entry validate-email" type="text" />


Step: 7 Find following code in login.phtml (password textbox).

<input type="password" name="login[password]" class="input-text required-entry validate-password" id="pass" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Password')) ?>" />

And replace with the following code. The code define the password of user if that user select remember me option.

<input name="login[password]" type="password" class="input-text required-entry validate-password"  value="<?php if($cookie_user_password != ''){ echo $cookie_user_password;}?>" />

Step: 8 Add the following code at the place where you want to display checkbox for the functionality of remember me on page.

<div>
                            <input type="checkbox" name="rememberme" value="remember" <?php if($rememberme != ''){ echo "checked";} ?>  /> Remember me.

                        </div>

Monday, 16 May 2016

how to call a custom phtml file on CMS Page and blocks (Admin panel) magento 2


Calling in blocks and cms pages

{{block class="Magento\Framework\View\Element\Template" name="test_file" template="Magento_Theme::html/test.phtml"}}

Thursday, 12 May 2016

how to order canceled by code on magento 2

require_once '../app/Mage.php';
    umask(0);
    Mage::app('default');
    Mage::getSingleton('core/session', array('name'=>'frontend'));
   

    //$toDate = date('Y-m-d H:i:s', strtotime("-3 minutes"));
    $toDate = date('Y-m-d H:i:s', strtotime("-96 hours"));
   
    $orderCollection = Mage::getModel('sales/order')->getCollection()
        ->addAttributeToFilter('created_at', array('to'=>$toDate))
        ->addFieldToFilter('status', 'pending');
      
    foreach($orderCollection as $_order)
    {
        $order = Mage::getModel('sales/order')->load($_order['entity_id']);
      
        if($order->canCancel())
        {
        $order->cancel();
        $comment = 'Order marked as cancelled';
        $isCustomerNotified =true;
        $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, "canceled", $comment, $isCustomerNotified);
       
        $order->save();
        $order->sendOrderUpdateEmail(true, $comment);

    }   
    }

Tuesday, 3 May 2016

how to remove space before body class on magento

/app/code/core/Mage/Page/Block/Html.php  (Line number 157)

public function getBodyClass()
{
    return trim($this->_getData('body_class');
}

Tuesday, 26 April 2016

how to find the position of a product in a magento category

$productPositions = Mage::getResourceModel('catalog/category')->getProductsPosition($category);
                    $productPositions[$_product->getId()];

Monday, 18 April 2016

sort products by most sold, reviews" in products list page

sort products by most sold, reviews" in products list page

for ->Sorting by rating

Copy the file

app/code/core/Mage/Catalog/Block/Product/List.php to

app/code/local/Mage/Catalog/Block/Product/List.php

in list.php find for this line

$this->_productCollection =$layer->getProductCollection();

which will be in around line no 86 add the following code after that

$this->_productCollection->joinField('rating_summary', 'review_entity_summary', 'rating_summary', 'entity_pk_value=entity_id', array('entity_type'=>1, 'store_id'=> Mage::app()->getStore()->getId()), 'left');

now copy

app/code/core/Mage/Catalog/Model/Config.php

to

app/code/local/Mage/Catalog/Model/Config.php

in config.php find for this code

$options = array(
    'position'  => Mage::helper('catalog')->__('Position')
);

replace with

$options = array(
    'position'  => Mage::helper('catalog')->__('Position'),
    'rating_summary' => Mage::helper('catalog')->__('Rating')
);

====================================================

-->>for BESTSELLER

follow this procedure create a folder naming Company and inside that folder place Catalog and inside catalog create 3 folders Block,etc and Model In Block add Product in Product add List and in List create a file and name it as Toolbar.php and ad this code into it

<?php
class Company_Catalog_Block_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
{
    public function setCollection($collection)
    {
        parent::setCollection($collection);

        if ($this->getCurrentOrder()) {
            if($this->getCurrentOrder() == 'qty_ordered') {
                $this->getCollection()->getSelect()
                     ->joinLeft(
                            array('sfoi' => $collection->getResource()->getTable('sales/order_item')),
                             'e.entity_id = sfoi.product_id',
                             array('qty_ordered' => 'SUM(sfoi.qty_ordered)')
                         )
                     ->group('e.entity_id')
                     ->order('qty_ordered ' . $this->getCurrentDirection());
            } else {
                $this->getCollection()
                     ->setOrder($this->getCurrentOrder(), $this->getCurrentDirection())->getSelect();
            }
        }

        return $this;
    }
}


now in etc folder create a file with name config.xml and add this code

<config>
    <modules>
        <Company_Catalog>
            <version>0.1.0</version>
        </Company_Catalog>
    </modules>
    <global>
        <blocks>
            <catalog>
                <rewrite>
                    <product_list_toolbar>Inchoo_Catalog_Block_Product_List_Toolbar</product_list_toolbar>
                </rewrite>
            </catalog>
        </blocks>
        <models>
            <catalog>
                <rewrite>
                    <config>Inchoo_Catalog_Model_Config</config>
                </rewrite>
            </catalog>
            <catalog_resource>
                <rewrite>
                    <product_collection>Inchoo_Catalog_Model_Resource_Product_Collection</product_collection>
                </rewrite>
            </catalog_resource>
        </models>
    </global>
</config>

Now in Model create a file naming Config.php and add this code.

<?php class Company_Catalog_Model_Config extends Mage_Catalog_Model_Config
{
    public function getAttributeUsedForSortByArray()
    {
        return array_merge(
            parent::getAttributeUsedForSortByArray(),
            array('qty_ordered' => Mage::helper('catalog')->__('Sold quantity'))
        );
    }
}

also create Resource folder in Model and in Resource folder create Product folder and create a file naming Collection.php and add following code.

<?php
class Company_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_Resource_Product_Collection
{
    protected function _getSelectCountSql($select = null, $resetLeftJoins = true)
    {
       $this->_renderFilters();
       $countSelect = (is_null($select)) ?
           $this->_getClearSelect() :
           $this->_buildClearSelect($select);

       if(count($countSelect->getPart(Zend_Db_Select::GROUP)) > 0) {
           $countSelect->reset(Zend_Db_Select::GROUP);
       }

       $countSelect->columns('COUNT(DISTINCT e.entity_id)');
       if ($resetLeftJoins) {
           $countSelect->resetJoinLeft();
       }
       return $countSelect;
    }
}


Now finally activate this module by going to app/etc/modules create a file Company_Catalog.xml add this code.

<?xml version="1.0"?>
<!--
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Connect
 * @copyright   Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
-->
<config>
    <modules>
        <Company_Catalog>
            <active>true</active>
            <codePool>community</codePool>
            <depends />
        </Company_Catalog>
    </modules>
</config>

Thursday, 14 April 2016

how get Selected filter In layered navigation magento


All the applied filters are stored in layer state object. You can easily retrieve them by using the following snippet:

$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();

 foreach ($appliedFilters as $item) {
    $item->getName(); // Name of the filter
    $item->getLabel(); // Currently selected value
    $item->getFilter()->getRequestVar();
    }

Wednesday, 24 February 2016

database server does not support the InnoDB storage engine.


Line 59 of the file app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php
Replace:
    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW VARIABLES');
        return (!isset($variables['have_innodb']) || $variables['have_innodb'] != 'YES') ? false : true;
    }
   
   
    with this:
   
    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW ENGINES');
        return (isset($variables['InnoDB']) && $variables['InnoDB'] != 'NO');
    }

Thursday, 18 February 2016

how to get logged In customer’s details on magento

 // Check if any customer is logged in or not
if (Mage::getSingleton('customer/session')->isLoggedIn()) {

    // Load the customer's data
    $customer = Mage::getSingleton('customer/session')->getCustomer();

    $customer->getPrefix();
    $customer->getName(); // Full Name
    $customer->getFirstname(); // First Name
    $customer->getMiddlename(); // Middle Name
    $customer->getLastname(); // Last Name
    $customer->getSuffix();

    // All other customer data
    $customer->getWebsiteId(); // ID
    $customer->getEntityId(); // ID
    $customer->getEntityTypeId(); // ID
    $customer->getAttributeSetId(); // ID
    $customer->getEmail();
    $customer->getGroupId(); // ID
    $customer->getStoreId(); // ID
    $customer->getCreatedAt(); // yyyy-mm-ddThh:mm:ss+01:00
    $customer->getUpdatedAt(); // yyyy-mm-dd hh:mm:ss
    $customer->getIsActive(); // 1
    $customer->getDisableAutoGroupChange();
    $customer->getTaxvat();
    $customer->getPasswordHash();
    $customer->getCreatedIn(); // Admin
    $customer->getGender(); // ID
    $customer->getDefaultBilling(); // ID
    $customer->getDefaultShipping(); // ID
    $customer->getDob(); // yyyy-mm-dd hh:mm:ss
    $customer->getTaxClassId(); // ID
}

Monday, 15 February 2016

how to ip track location country

$key='4aa3d8dd845debd79b15b3d55449dbeddbf00645e0acdd2b943a99f298b9c089';
    $ip=$_SERVER['REMOTE_ADDR'];
$url='http://api.ipinfodb.com/v3/ip-country/?key='.$key.'&ip='.$ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    $dataArr=explode(";",$data);
    if($dataArr[3]=="IN"){
        //echo "<pre>"; print_r($dataArr); echo "</pre>"; exit;
        header("Location: ./india");
        exit;
    }

Tuesday, 9 February 2016

magento custom search by name ,description short_description

// Code to Search Product by $searchstring and get Product IDs
    $product_collection = Mage::getResourceModel('catalog/product_collection')
                 ->addAttributeToSelect('*')
                 ->addAttributeToFilter('name', array('like' => '%'.$searchstring.'%'))
                 ->load();

    foreach ($product_collection as $product) {
        $ids[] = $product->getId();
    }

Sunday, 7 February 2016

How can I find all products without images in Magento?

//this builds a collection that's analagous to
//select * from products where image = 'no_selection'
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('visibility', 4)->addAttributeToFilter('status', 1)->addAttributeToFilter('image', 'no_selection');

foreach($products as $product)
{
    echo  $product->getSku() . " has no image \n<br />\n";
    //var_dump($product->getData()); //uncomment to see all product attributes
                                     //remove ->addAttributeToFilter('image', 'no_selection');
                                     //from above to see all images and get an idea of
                                     //the things you may query for
}

Thursday, 4 February 2016

How to retrieve a customer by phone number in magento?

$customer = Mage::getResourceModel('customer/address_collection')
    ->addAttributeToSelect('telephone')
    ->addAttributeToFilter('telephone', $phoneNumber)
    ->getFirstItem()->getCustomer();
if ($customer !== false) {
    // Do stuff...
}

Wednesday, 13 January 2016

Magento admin order details Next and Previous order

/*************************************************************************/
        $conn = Mage::getSingleton('core/resource')->getConnection('core_read');
        $sql="SELECT sum(total_qty) as shipqty FROM sales_flat_shipment WHERE order_id=".$_order->getentity_id()." GROUP BY order_id  ";
        $results = $conn->fetchOne($sql);
        $per=($results/$total)*100;
        $orderAdminDate = $this->formatDate($_order->getCreatedAtDate(), 'medium', true);
        $orderStoreDate = $this->formatDate($_order->getCreatedAtStoreDate(), 'medium', true);
      
        $preOrderId=0;
        $nextOrderId=0;
        $curOrderId=0;
        $curOrderId=$_order->getId();
      
        $resource = Mage::getSingleton('core/resource');
        $tableName = $resource->getTableName('sales_flat_order');
        $readConnection = $resource->getConnection('core_read');
        $query = 'SELECT entity_id FROM ' . $tableName . ' WHERE entity_id < '.$curOrderId.' ORDER BY entity_id DESC LIMIT 0,1';
        $preOrderId = $readConnection->fetchOne($query);
      
        $query = 'SELECT entity_id FROM ' . $tableName . ' WHERE entity_id > '.$curOrderId.' ORDER BY entity_id ASC LIMIT 0,1';
        $nextOrderId = $readConnection->fetchOne($query);







?>
<?php //* ?>
<div style="width:300px;">
<?php if($preOrderId>0) { ?>
<div style="float:left" ><a href="<?php echo $this->getViewUrl($preOrderId) ?>" style="font-weight:bold">&laquo; Previous Order &nbsp;    </a></div>
<?php } else { ?>
<div style="float:left" >&laquo; Previous Order &nbsp;  </div>
<?php } if($nextOrderId>0) { ?>
<div style="float:right" ><a href="<?php echo $this->getViewUrl($nextOrderId) ?>" style="font-weight:bold">&nbsp;Next Order &raquo;</a></div>
<?php } else { ?>
<div style="float:right" >&nbsp;Next Order &raquo;</div>
<?php } ?>
</div>
<?php //*/ ?>

Tuesday, 5 January 2016

Magento: Get a configurable products associated simple product data

$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();

Sunday, 3 January 2016

Magento Product Offer time count

       <?php
                $toDate = $_product->getSpecialTODate();
                $count = 1;
               
               
                if($toDate && strtotime($toDate)>time()){
                    $date = new DateTime($toDate);
                    ?>
                    <input type="hidden" id="todate" value="<?php echo $date->format('m/d/Y')?>" />
                    <div class="time_d">
                        <span class="countdown_section dealcountday">
                            <span class="countdown_amount" id="dealcountday"></span>
                        </span>
                       
                        <span class="countdown_section">
                            <span class="countdown_amount" id="dealcounthour"></span>
                           
                            <span class="countdown_amount min" id="dealcountmin"></span>
                          
                            <span class="countdown_amount sec" id="dealcountsec"></span>
                           
                            <span class="countdown_amount milisec" id="dealcountmilisec"></span>
                        </span>
                    </div>
                    
               
                    <script language="JavaScript">
                        var todate = document.getElementById("todate").value;
                        date = new Date(todate);
                        var target_date = date.getTime();
                        var weeks,days, hours, minutes, seconds;
                        var countdown = document.getElementById("dealcounthour");
                       
                       
                        setInterval(function () {
                       
                            var current_date = new Date().getTime();
                            var totalseconds_left = (target_date - current_date) ;
                            var seconds_left = (target_date - current_date) / 1000;
                           
                            days = parseInt(seconds_left / 86400);
                            if (days>0) {
                            seconds_left = seconds_left % 86400;
                            }
                            if (days<=0) {
                                dealcountday.style.display = "none";
                            }
                            hours = parseInt(seconds_left / 3600);
                            seconds_left = seconds_left % 3600;
                            minutes = parseInt(seconds_left / 60);
                            seconds = parseInt(seconds_left % 60);
                           
                            miliseconds= (totalseconds_left % 1000); //alert(seconds);
                           
                            dealcountday.innerHTML =  "<strong>"+days+"</strong>" + ' Day(s)';
                            dealcounthour.innerHTML =   "<strong>"+hours+": </strong>" ;
                            dealcountmin.innerHTML = "<strong>"+ minutes+": </strong>";
                            dealcountsec.innerHTML =  "<strong>"+seconds +': </strong>';
                            dealcountmilisec.innerHTML="<strong>"+miliseconds+"</strong>";
                        }, 10);
                    </script>
                <?php  } ?>