Call Block method from Controller in Magento

//Create Object of Block
$product = new Mage_Catalog_Block_Product_View();
print_r(get_class_methods($product));

Advertisements

What is a Helper ?

Create your own Helper

As you are now used to, it starts by declaring it in the config.xml of your plugin, do that in <global> and after </blocks>


<helpers>
    <test>
        <class>Pfay_Test_Helper</class>
    </test>
</helpers>

What is a Helper

As the name implies a « helper » is something that is right for you ! It is an object that will contain practical functions for you and you can call it from anywhere, you just load your helper to use it. For example:

$helper = Mage::helper(‘monhelper’);

Note that this call is actually equivalent to:

$helper = Mage::helper(‘monhelper/data’);
Indeed, it is the default helper « data » which is called.

Call helper of custom module

$helper = Mage::helper(‘modulename/helpername’);

Create your own Helper

As you are now used to, it starts by declaring it in the config.xml of your plugin, do that in <global> and after </blocks>


<helpers>
    <test>
        <class>Pfay_Test_Helper</class>
    </test>
</helpers>

Then creates the folder and the file app/code/local/Pfay/Test/Helper/data.php function wich will contains the function bytwo($ nbr) with a number as an argument and returns that number multiplied by two. A helper is an object that extends the core class Mage_Core_Helper_Abstract.

class Pfay_Test_Helper_Data extends Mage_Core_Helper_Abstract{
public function bytwo($nbr){
return $nbr*2;
}
}

Now in/app/code/local/Pfay/Test/Block/monblock.php we change the function by:

</div>
class Pfay_Test_Block_Monblock extends Mage_Core_Block_Template
{
public function methodblock()
{
$helper = Mage::helper('test');
return '2*2 = '.$helper->bytwo(2);
}
}

Now when we go on yoursite.com/index.php/test/index/, we see that it works!

Here we are ! you understand how to create a helper on magento, I invite you to practice, the only way to improve yourself ;) If you have any questions, feel free to leave a comment.

You want to help me? Share this article on twitter, do an article on this series of tutorials on your blog, tell your friends, participate in the comments and return to this site;)

Magento: Programmatically Updating SKUs in Bulk

Magento does not make it easy to change SKUs in bulk. Try to do it via the import/export or dataflow profiles and you run into all kinds of problems. There is, however, a fairly easy way to do it and it simply involves adding a php script to your server and a CSV file of before and after SKUs. Here’s the step-by-step;

Note: Be sure to test this with only one or two product SKUs before doing it with all your SKUs. Also, be sure to backup your database before attempting this.

1. Create a CSV File with Before and After SKUs

In the first column, list your current SKUs and in the second column list the new SKUs.

Do not include headings in your CSV file.

Be sure this file is saved as a CSV file in the UTF-8 or ANSI encoding. You might run into problems with this if you create the file using Excel.

2. Put the CSV File on Your Server

Upload the CSV file to the var/export directory on your Magento server so that it’s path is /var/export/sku2sku.csv.

3. Create the PHP Script

On your server, in your Magento installation directory (the one where you see the app, var, skin, media, js and other directories), create a new file, save it, and name it “updateskus.php”.

Paste the following php code into updateskus.php and save the file.

</pre>
<?php
include_once './app/Mage.php';
Mage::app();
$updates_file="./var/export/sku2sku.csv";
$sku_entry=array();
$updates_handle=fopen($updates_file, 'r');
if($updates_handle) {
       while($sku_entry=fgetcsv($updates_handle, 1000, ",")) {
            $old_sku=$sku_entry[0];
            $new_sku=$sku_entry[1];
            echo "<br>Updating ".$old_sku." to ".$new_sku." - ";
            try {
                   $get_item = Mage::getModel('catalog/product')
                               ->loadByAttribute('sku', $old_sku);
                   if ($get_item) {
                          $get_item->setSku($new_sku)->save();
                          echo "successful";
                    } else {
                          echo "item not found";
                    }
                } catch (Exception $e) {
                    echo "Cannot retrieve products from Magento: ".$e->getMessage()."<br>";
                    return;
                }
        }
}
fclose($updates_handle);
?>

4. Run the Script

To run the script simply use your internet browser and navigate to http://yoursite.com/updateskus.php. If you have a multi-site setup use the master or primary site as set by your hosting provider.

When the page opens you should see confirmation messages that your SKUs were updated. Your SKUs should now be successfully updated.

If you’re finished updating the SKUs, remove the CSV and PHP files that you added to the server.

5. Errors

If you run into the following error, don’t worry too much. Just re-run the script and see if more SKUs get updated.

Cannot retrieve products from Magento: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

If you have a lot of SKUs to update you can expect the script to take several minutes at least, to complete.

This method was tested on a multi-site Magento Community 1.6.1 installation.

Magento get total quantity of product sold

$id = 123; // enter your product ID here
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToFilter('id', $id)
    ->setOrder('ordered_qty', 'desc')
    ->getFirstItem();
$product = $_productCollection;

echo 'Already Bought '.(int)$product->ordered_qty;

How to get product rating and review in magento


/**
* Getting reviews collection object
*/

$productId = $product->getId();
$reviews = Mage::getModel('review/review')
->getResourceCollection()
->addStoreFilter(Mage::app()->getStore()->getId()) 
->addEntityFilter('product', $productId)
->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
->setDateOrder()
->addRateVotes();


/**
* Getting average of ratings/reviews
*/

$avg = 0;
$ratings = array();
if (count($reviews) > 0) {
foreach ($reviews->getItems() as $review) {
foreach( $review->getRatingVotes() as $vote ) {
$ratings[] = $vote->getPercent();
}
}
$avg = array_sum($ratings)/count($ratings);
}

All Catogory Listing in Magento

Some time we wants to display all categories in homepage or
any CMS pages in Magento. There are many different ways to
get the category listing. I will show you how you can get
list of all categories of your Magento Shop.

<strong>1. Display all the Magento Categories(Active/Inactive)</strong>

The following code will fetch all categories (both active
 and inactive) that are presented in your Magento Store.

$categories = Mage::getModel('catalog/category')
              ->getCollection()->addAttributeToSelect('*');

<strong>2. Display All Active Categories</strong>

The following code will fetch all active categories that
are present in your Magento Store. Filtering the inactive categories.

$categories = Mage::getModel('catalog/category')
             ->getCollection()->addAttributeToSelect('*')->addIsActiveFilter();

<strong>3. Display Active Categories Of Any Particular Level in Magento</strong>

The following code will fetch all active categories of certain/specific
 level. Here, I have chosen level 1. Also sorting categories by name.

$categories = Mage::getModel('catalog/category')
              ->getCollection()
              ->addAttributeToSelect('*')
              ->addIsActiveFilter()
              ->addLevelFilter(1)
              ->addOrderField('name');

<strong>4. Display Store Specific Categories</strong>

The following code will fetch all active store specific categories.

getStoreCategories($sorted=false, $asCollection=false, $toLoad=true)

$helper = Mage::helper('catalog/category');

// sorted by name, fetched as collection
$categoriesCollection = $helper->getStoreCategories('name', true, false);

// sorted by name, fetched as array
$categoriesArray = $helper->getStoreCategories('name', false, false);

<strong>5. Display Top level categories only in Magento</strong>

The following code will fetch all the Top level categories only

<?php
      $_helper = Mage::helper('catalog/category')
      $_categories = $_helper->getStoreCategories()
      if (count($_categories) > 0):
 ?>
<ul>
    <?php foreach($_categories as $_category): ?>
      <li>
         <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
         <?php echo $_category->getName() ?>
        </a>
     </li>
   <?php endforeach; ?>
</ul>
<?php endif; ?>

<strong>6. Display Top Level Categories as well as ALL Subcategories in Magento</strong>

The following code will fetch all the Top Level Categories as
well as ALL Subcategories

<?php
      $_helper = Mage::helper('catalog/category')
      $_categories = $_helper->getStoreCategories()
      $currentCategory = Mage::registry('current_category')
      if (count($_categories) > 0):
?>
<ul>
   <?php foreach($_categories as $_category): ?>
     <li>
        <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
          <?php echo $_category->getName() ?> //Top Level Category Listing
        </a>
        <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
        <?php $_subcategories = $_category->getChildrenCategories() ?>
        <?php if (count($_subcategories) > 0): ?>
        <ul>
            <?php foreach($_subcategories as $_subcategory): ?>
            <li>
              <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"> //Sub Category Listing
                 <?php echo $_subcategory->getName() ?>
              </a>
            </li>
           <?php endforeach; ?>
       </ul>
       <?php endif; ?>
    </li>
  <?php endforeach; ?>
</ul>
<?php endif; ?>

<strong>7. Display Subcategories only for the Current Top Category</strong>

The following code will fetch all Subcategories only for the
Current Top Category

<?php $_currentCategory = Mage::register('current_category') ?>
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>" title="<?php echo $_category->getName() ?>">
<?php echo $_category->getName() ?>
</a>
<?php if ($_category->getId() == $_currentCategory->getId()): ?>
<?php $_subcategories = $_currentCategories->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>" title="<?php echo $_subcategory->getName() ?>">
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?></pre>
<h6 class="zemanta-related-title" style="font-size: 1em;">Related articles</h6>
<ul class="zemanta-article-ul">
	<li class="zemanta-article-ul-li"><a href="http://singhnarendra434.wordpress.com/2013/07/29/display-categories-and-subcategories-in-magento/" target="_blank">Display Categories and SubCategories in Magento</a> (singhnarendra434.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="http://singhnarendra434.wordpress.com/2013/07/24/show-all-category-on-magento-sidebar/" target="_blank">Show all category on magento sidebar</a> (singhnarendra434.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="http://singhnarendra434.wordpress.com/2013/07/24/add-magento-category-links-to-your-footer-template/" target="_blank">Add Magento Category Links to your Footer Template</a> (singhnarendra434.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/27/add-custom-sort-by-drop-down-menu-options-in-magento/" target="_blank">Add Custom "Sort By" Drop Down menu options In Magento</a> (magentofresher.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/31/magento-image-switcher-on-mouseover-more-view-product-page/" target="_blank">Magento More View Image Switcher On MouseOver Product Page</a> (magentofresher.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/26/basic-magento-functions-to-get-category-information/" target="_blank">Basic Magento Functions to get Category Information</a> (magentofresher.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="http://onlinemagento.wordpress.com/2013/07/25/magento-code-book/" target="_blank">Magento Code Book</a> (onlinemagento.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/26/basic-magento-functions-to-get-cart-information/" target="_blank">Basic Magento Functions to get Cart Information</a> (magentofresher.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/31/magento-product-and-category-related-functions/" target="_blank">Magento Product and Category Related Functions</a> (magentofresher.wordpress.com)</li>
	<li class="zemanta-article-ul-li"><a href="https://magentofresher.wordpress.com/2013/07/30/magento-frequently-used-fuctions/" target="_blank">Magento Frequently used fuctions</a> (magentofresher.wordpress.com)</li>
</ul>
<pre>

Magento Product and Category Related Functions

Magneto Product Collection

$collection = Mage::getModel(‘catalog/product’)->getCollection()->addAttributeToSelect(‘*’);

Get product of particular category

$products = Mage::getModel(‘catalog/category’)->load(category_id); //put your category id here
$productslist = $products->getProductCollection()->addAttributeToSelect(‘*’);

Product details from Product ID.

$productid=1234;
$model = Mage::getModel(‘catalog/product’) //getting product model
$_product = $model->load($productid); //getting product object for particular product id
echo $_product->getShortDescription(); //product’s short description
echo $_product->getDescription(); // product’s long description
echo $_product->getName(); //product name
echo $_product->getPrice(); //product’s regular Price
echo $_product->getSpecialPrice(); //product’s special Price
echo $_product->getProductUrl(); //product url
echo $_product->getImageUrl(); //product’s image url
echo $_product->getSmallImageUrl(); //product’s small image url
echo $_product->getThumbnailUrl(); //product’s thumbnail image url

product collection from the category and then refine it down from there.

$products = Mage::getModel(‘catalog/category’)->load(410)
->getProductCollection()
->addAttributeToSelect(‘*’)
->addAttributeToFilter(‘status’, 1)
->addAttributeToFilter(‘visibility’, 4)
->addAttributeToFilter(‘special_price’, array(‘neq’ => “”))
->addAttributeToFilter(‘discontinued’, array(‘neq’ => 1))
->setOrder(‘price’, ‘ASC’);

Get Current product category id

$_helper = $this->helper(‘catalog/output’);
$_category_detail=Mage::registry(‘current_category’);
echo $_category_detail->getName(); //gives current category name
echo $_category_detail->getId(); //gives current category id

Display all categories in magento

function get_categories(){
$category = Mage::getModel(‘catalog/category’);
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$arr = array();
if ($ids){
foreach ($ids as $id){
$cat = Mage::getModel(‘catalog/category’);
$cat->load($id);
$arr[$id] = $cat->getName();
}
}
return $arr;
}
$arr = get_categories();
$arr = array_flip($arr);

Get Parent Category of current category

echo $cat_idd = $this->getCurrentCategory()->getParentCategory()->getId();

Get the category ID by product id

$productObj = Mage::getModel(‘catalog/product’)->load($product_id);
$categoryIds = $productObj->getCategoryIds();

To find the parent ID of current category

$_cat = new Mage_Catalog_Block_Navigation();
$curent_cat = $_cat->getCurrentCategory();
$curent_cat_id = $curent_cat->getId();

Get all categories for a product in Magento

$product = Mage::getModel(‘catalog/product’)->load($productId);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel(‘catalog/category’)->load($category_id) ;
echo $_cat->getName();
}