Wednesday 16 December 2015

Magento 2 - Get Category, Products and Customer data using outside script (Programatically get & edit data)

First Create scripts/abstract.php file and add below code

<?php
use \Magento\Framework\AppInterface as AppInterface;
use \Magento\Framework\App\Http as Http;

use Magento\Framework\ObjectManager\ConfigLoaderInterface;

use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList as AreaList;
use Magento\Framework\App\State as State;

abstract class AbstractApp implements AppInterface

{
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        Event\Manager $eventManager,
        AreaList $areaList,
        RequestHttp $request,
        ResponseHttp $response,
        ConfigLoaderInterface $configLoader,
        State $state,
        Filesystem $filesystem,
        \Magento\Framework\Registry $registry
    ) {
        $this->_objectManager = $objectManager;
        $this->_eventManager = $eventManager;
        $this->_areaList = $areaList;
        $this->_request = $request;
        $this->_response = $response;
        $this->_configLoader = $configLoader;
        $this->_state = $state;
        $this->_filesystem = $filesystem;
        $this->registry = $registry;
    }

    public function launch()

    {
        $this->run();
        return $this->_response;
    }

    abstract public function run();


    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)

    {
        return false;
    }
}
?>

For category Data:

create scripts/categoryData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CategoriesDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $category = $this->_objectManager->create('\Magento\Catalog\Helper\Category');
        $_categories = $category->getStoreCategories();
        foreach($_categories as $cat){
            $_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
            $_category = $_category->load($cat->getId());
            $_subcategories = $_category->getChildrenCategories();
            if (count($_subcategories) > 0){
                echo $_category->getId().'=>'.$_category->getName().'<br/>';      
                foreach($_subcategories as $_subcategory){
                     echo "sub category: ".$_subcategory->getId().'=>'.$_subcategory->getName().'<br/>';
                }
            }
        }
        
        /* for load Specific category uncomment below code */
        //$_category = $this->_objectManager->create('\Magento\Catalog\Model\Category');
        //$_category = $_category->load(4); // your category Id
        //echo '<pre>';print_r($category->getData());
        //$category->delete();
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CategoriesDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/categoryData.php or direct run categoryData.php in your browser.

For Product Data:

create scripts/productData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class ProductsDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $products = $this->_objectManager->create('\Magento\Catalog\Model\Product');
        
        $products = $products->getCollection()
                    ->addAttributeToFilter('type_id', 'simple')
                    ->addAttributeToSelect('*')
                    ->load();
         foreach($products as $product)
         {
            echo $product->getId().'=>'.$product->getName().'=>'.$product->getData('price').'<br/>';
            
            $_product = $this->_objectManager->create('\Magento\Catalog\Model\Product')->loadByAttribute('entity_id',$product->getId());
            
         }
        
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('ProductsDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/productData.php or direct run productData.php in your browser.

For Customer Data:

create scripts/customerData.php and add below code for get category data and edit it programetically.

<?php
require dirname(__FILE__) . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/abstract.php';

class CustomersDataApp extends AbstractApp
{

    public function run()
    {
        $this->_objectManager->get('Magento\Framework\Registry')
            ->register('isSecureArea', true);

        $customers = $this->_objectManager->create('\Magento\Customer\Model\Customer');
        $customers = $customers->getCollection();
        
        foreach($customers as $customer)
        {
            //echo '<pre>';print_r($customer->getData());
            echo $customer->getId().'=>'.$customer->getName().'<br/>';    
            //$_customer = $this->_objectManager->create('\Magento\Customer\Model\Customer')->load($customer->getId()); /// Customer Object for change data or load Customer
        }
        
    }
}

/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('CustomersDataApp');
$bootstrap->run($app);
?>

Then just run command like php scripts/customerData.php or direct run customerData.php in your browser.

Hope this will help you, Thank you.

Thursday 3 July 2014

Date Picker in any form in Magento

open page.xml and put below code in 

<block type="page/html_head" name="head" as="head">between</block>

<action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>

<block type="core/html_calendar" name="head.calendar" as="calendar" template="page/js/calendar.phtml"></block>

now put below code where you want to show calendar:

<div class="field">
  <label for="delivery_date"><?php echo $this->__('Delivery Date') ?></label>
  <div class="input-box">
      <input type="text" id="_dob" name="delivery_date" class="input-text required-entry" /><em>*</em>
      <img title="Select date" id="_dob_trig" src="<?php echo $this->getSkinUrl('images/calendar.gif');?>" class="v-middle" />
   </div>
</div>

<script type="text/javascript">
//<![CDATA[
Calendar.setup({
inputField : '_dob',
ifFormat : '%m/%e/%y',
button : '_dob_trig',
align : 'Bl',
singleClick : true
});
//]]>
</script>

Saturday 31 May 2014

Programmatically get search result in magento

Below code use for get search result programetically

$searchText = 'mobile';
$query = Mage::getModel('catalogsearch/query')->loadByQueryText($searchText);
        $query->setStoreId(1);
        $query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
        $fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
                Mage::getModel('catalogsearch/fulltext'), 
                $searchText, 
                $query
                );
        $collection = Mage::getResourceModel('catalog/product_collection');
        $collection->getSelect()->joinInner(
                    array('search_result' => $collection->getTable('catalogsearch/result')),
                    $collection->getConnection()->quoteInto(
                        'search_result.product_id=e.entity_id AND search_result.query_id=?',
                        $query->getId()
                    ),
                    array('relevance' => 'relevance')
                );
using above code you will get your search result programetically in magento where $searchText is your search value.

Hope this code help you,
Thank you.

Tuesday 21 August 2012

Magento - Creating and Showing a static block in Frontend

The content of the blocks are created and modified from Magento Admin panel which can be placed on one or multiple pages. To create a static block you can follow some simple steps which are given bellow.

Creating a Static Block:


A. Go to the Magento Admin panel and then select the  CMS -> Static Blocks.
B. Then Click on the “Add New Block” button from the right top .
C. Now fillup the following fields:
  1. Block Title: Give the Name of the static block here. This will not show on the frontend.
  2. Identifier: Give the id of this block. It used as reference of this block, when adding to a template file or CMS page.
  3. Status: Its define visibility of this static block on the frontend.
  4. Content: Content of static block can be plain text, HTML code and Javascript. PHP code can’t use in this area.
D. After fillup all fields then click on “Save Block” button from the right top .

Showing a Static Block in Frontend:


A static block can be added to display on the frontend by some different ways which are discribed bellow:

1. Adding a static block to a CMS page From the Magento admin:
Go to CMS > Pages and click on a pre-existing page or create a new page where you want to show your static block.
Now use the following code in the Content field of the CMS page:

{{block type="cms/block" block_id="your_block_identifier" template="cms/content.phtml"}}

2. Adding a static block by using template phtml file:
Open your phtml file where you want to add the static block.
For Example: /app/design/frontend/your-instance-name/your_theme/template/callouts/right_col.phtml
Then you can use the following code in your phtml file to show the content of your ststic block:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('your_block_identifier')->toHtml() ?>




3. Adding a static block by using XML layout file:
Use the following code to show the content of static block by using Layout XML file:


<reference name="content/left/right">
       <block type="cms/block" name="your_block_name" before="-">
        <action ethod="setBlockId"><block_id>your_block_identifier</block_id></action>
      </block>
 </reference>


Note: You can use the above code to show the block content in specific page by using “ Layout Update XML ” field of CMS page.
To do this go: CMS -> pages from your magento backend. Then click on on that page where you want to show the static block.
Then click on Design tab from left panel like:

Now Past the above code in Layout Update XML  field.
here i wrote <reference name=”content/left/right”> in code. You must use only one like- content / left or right as your reference name.



PHP - Browser Detection code

Past below code in you site to detecte browser : 

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

Magento - Previous/Next link in product page


Below code Use for show previous/next link in product page:

open view.phtml file (app/design/frontend/base(or your theme interface)/default(your theme interface)/template/catalog/product/view.phtml)

past below code above <div class="product-view">

<!-- Product Navigation -->
<div id="product-navigation">
  <?php // Previous and Next product links in product page
      if ($this->helper('catalog/data')->getCategory()) {
         $cat = $this->helper('catalog/data')->getCategory();
      } else {
         $_ccats = $this->helper('catalog/data')->getProduct()->getCategoryIds();
         $cat = Mage::getModel('catalog/category')->load($_ccats[0]);
      }; //missing ";" causes 503 error for validation service
                
     $_product = $this->getProduct();
                 
     if(!$_product->getCategoryIds())
     return; // Don't show Previous and Next if product is not in any category
                 
                 
     $order = Mage::getStoreConfig('catalog/frontend/default_sort_by');
     $direction = 'asc'; // asc or desc
                 
     $category_products = $cat->getProductCollection()->addAttributeToSort($order, $direction);
     $category_products->addAttributeToFilter('status',1); // 1 or 2
     $category_products->addAttributeToFilter('visibility',4); // 1.2.3.4
                 
     $cat_prod_ids = $category_products->getAllIds(); // get all products from the category
     $_product_id = $_product->getId();
                 
     $_pos = array_search($_product_id, $cat_prod_ids); // get position of current product
     $_next_pos = $_pos+1;
     $_prev_pos = $_pos-1;
                 
     // get the next product url
    if( isset($cat_prod_ids[$_next_pos]) ) {
       $_next_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_next_pos] );
    } else {
       $_next_prod = Mage::getModel('catalog/product')->load( reset($cat_prod_ids) );
    }
      
    // get the previous product url
    if( isset($cat_prod_ids[$_prev_pos]) ) {
        $_prev_prod = Mage::getModel('catalog/product')->load( $cat_prod_ids[$_prev_pos] );
    } else {
        $_prev_prod = Mage::getModel('catalog/product')->load( end($cat_prod_ids) );
    }

    $more_url = $cat->getUrl();
    $nxtname=substr($_next_prod->getName(),0,25);
    $prvname=substr($_prev_prod->getName(),0,25);
    
  ?>
  <style>
   .prelinknav{float: left;width: 33%;font-size: 11px;text-align: left;}
   .nxtlinknav{float: left;width: 33%;font-size: 11px;text-align: right;}
   .catlinknav{float: left;width: 33%;font-size: 11px;text-align: center;}
   .product-view{float: left;}
                 
 </style>
 <div>
   <?php if($_prev_prod != NULL): ?>
    <div class="prelinknav"><a href="<?php print $_prev_prod->getUrlPath(); if($search_parameter):?>?search=1<?php endif;?>" ><span 

style="font-weight: bolder;"><?php echo $this->__('<<< PREVIOUS') ?></span>(<?php echo $prvname; ?>)</a></div>
   <?php endif; ?>
     <div class="catlinknav"><a href="<?= $more_url; ?>"><span style="font-weight: bolder;">Back</span>(<?php echo $cat->getName() ?>)

</a></div>
   <?php if($_next_prod != NULL): ?>
     <div class="nxtlinknav"><a href="<?php print $_next_prod->getUrlPath(); if($search_parameter):?>?search=1<?php endif;?>"><span 

style="font-weight: bolder;"><?php echo $this->__('NEXT') ?></span>(<?php echo $nxtname; ?>)<span style="font-weight: bolder;"><?php echo 

$this->__('>>>') ?></span></a></div>
   <?php endif; ?>
 </div>
</div>
<!-- end pagination nav -->

now check in frontend product view page

Magento - Product Price without decimal points

If you want to remove decimal points from Price ( front-end ) then use following steps :


Step 1:

Change the following file to remove the decimal points:

go to : lib/Zend/Currency.php

In the “toCurrency” function add the following line:

$options['precision'] = 0; around 184 line
above this :

$value    = Zend_Locale_Format::toNumber($value, array('locale'        => $locale,
                                                               'number_format' => $format,
                                                               'precision'     => $options['precision']));
replace to :
$value    = Zend_Locale_Format::toNumber($value, array('locale'        => $locale,
                                                               'number_format' => $format,
                                                               'precision'     => 0));


Step 2:

Change the following price to round the price:

app/code/core/Mage/Core/Model/Store.php

Change in method “roundPrice()” to the round prices in product listing and view pages like this:

return round(ceil($price), 0 );

like this :

public function roundPrice($price)
{
        //return round($price, 0);
        return round(ceil($price), 0 );
}

Please let me know if you have any questions