HTML/JavaScript

Monday, July 20, 2015

How to use Collection in Magento

A collection is basically a Model type containing other Models, it is basically used in Magento to handle product lists (ie. from a category or a bundle option), but not only.

Product Collection class in magento is Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection.

Here is some Sort of code snippet for Magento Collection(s).

Get All Products of a category

$collection = Mage::getResourceModel('catalog/product_collection')
->setStoreId($this->getStoreId())
->addCategoryFilter($category);

Tn this the addCategoryFilter() function, is used to get all products of a particular category. So, if you want to get all products of a certain category use this function.

Visibility Filter
———————
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($collection);

The addVisibleFilterToCollection() adds visibility filter to a product collection i.e only products which are visible in frontend. The product which have “Not Visible Individually” selected in admin are removed.

Status Filter
—————–
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);

This basically filters out products which are “Disabled”. Only “Enabled” products remain in the collection.

Add Product Price To Collection
——————————————–
$collection = Mage::getResourceModel('catalog/product_collection');
$collection ->addMinimalPrice()
->addFinalPrice()
->addTaxPercents();

This adds the product prices, i.e base price, final price etc to the collection. Also, price after tax, if applicable.

Filter By Ids
—————–
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addIdFilter(array(1,2,3));
//$collection->addIdFilter(array(1,2,3),false);

This puts an id filter, only product with ids 1,2,3 remain in the collection. The function parameter is true/false, this means include/exclude products from collection.

Add Website ID to the collection
——————————————–
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addWebsiteNamesToResult();

This adds website_id of each product to that collection. Only useful when using multiple websites in magento.

Filter Current Store Products
—————————————
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addStoreFilter();

Filter Current Website Products
——————————————-
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addWebsiteFilter();

Get All Products Ids
—————————
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getAllIds();

This returns an array with only products ids of collection.

Add SEO Product URL
——————————
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addUrlRewrite();

This adds SEO friends urls to our product collection.

Add Category Ids
————————
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryIds();

This will add category ids to the products.

Add Tier Pricing
————————
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addTierPriceData();

This added tier pricing data to each product in the collection.While we are on this subject, let look at some important function of the Product Object as well.

Want to add to cart configrurable product instead of drop down--


<!-- FOR THE ASSOCIATED PRODUCTS-->
<?php  $config_product_id = Mage::registry('current_product')->getId();?>
<?php  //if ($_product->isSaleable() && count($_attributes)):?>
<?php
 $product=Mage::getModel('catalog/product')->load($config_product_id);
  $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
   $attributeOptions = array();
     $ids = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($product->getId()); //get the children ids through a simple query
$_subproducts = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('entity_id', $ids)
    ->addAttributeToSelect('*');
    $prod_img=array();
   foreach($_subproducts as $_sub_prod){
    $prod_name [] = $_sub_prod->getName();
//    echo  Mage::helper('catalog/image')->init($_sub_prod, 'small_image')->resize(50,50);;
    $prod_img[] = $_sub_prod->getImageUrl();
    $asso_prod_id[] = $_sub_prod->getId();
    }
 //  print_r($img);die;
    $i=0;$j=0;
   foreach ($productAttributeOptions as $productAttribute) {
    foreach ($productAttribute['values'] as $attribute) {?>
     <form id="childproduct_addtocart_form_<?php echo $config_product_id?>" onsubmit="return addToCart(this);" method="post" action="<?php echo Mage::getBaseUrl();?>checkout/cart/add?product=<?php echo $config_product_id?>&super_attribute[<?php echo $productAttribute['attribute_id']; ?>]=<?php echo $attribute['value_index']?>">
       <?php echo $this->getBlockHtml('formkey') ?>
<?php

      echo $prod_name[$i];
    //  echo $prod_img[$j].'-'.$i;
      echo  "<img src=".$prod_img[$j]." width='100px'>";
    echo "price: ".$attribute['pricing_value']. "---". " Color: ".$attribute['store_label']." ---- "."" ;
      
     ?>   
     <input id="qty-<?php echo $asso_prod_id;?>" class="input-text qty" type="number" title="Aantal" value="1" maxlength="12" max="100" min="0" name="qty">
       <input type="hidden" value="<?php echo $config_product_id?>" name="product">
       <input type="hidden" value="" name="related_product">
        <input type="hidden" value="<?php echo $attribute['value_index']?>" name="super_attribute[<?php echo $productAttribute['attribute_id']; ?>]">
     <button class="cart_button" title="In winkelwagen" type="submit">Add To Cart</button>
     </form>
<?php
    $i++;$j++;}
}
//echo '<pre>';


    //print_r($_subproducts);
   

?>

Tuesday, June 16, 2015

Category Custom attribute

<?php

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->removeAttribute('catalog_category','category_color');

$setup->addAttribute('catalog_category', 'category_color', array(
    'group'         => 'General Information',
    'input'         => 'select',
    'type'          => 'varchar',
    'label'         => 'Select Product Layout',
    'option'        => array (
                              'value' => array('optionone'=>array(0=>'2 Products'),'optiontwo'=>array(0=>'3 Products'))
                       ),

    'backend'        => 'eav/entity_attribute_backend_array',
    'visible'       => 1,
    'required'      => 0,
    'user_defined' => 1,
    'default'      =>3,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$installer->endSetup();
?>

Tuesday, July 29, 2014

Import large .sql file into MySQL

C:\> mysql -hlocalhost -uroot -proot

mysql> SHOW VARIABLES LIKE 'wait_timeout';

If this is very low (e.g. 30 seconds) then increase it (e.g. 5 minutes):

mysql> SET SESSION wait_timeout = 300;
mysql> SET SESSION interactive_timeout = 300;

Then execute your SQL file (issue a USE `db` if necessary):
mysql> use TUTORIALS;

mysql> \. database.sql

Friday, July 25, 2014

“The service is unavailable.” Magento admin links

Issue was with some kind of Zend cache! I simply went to magento/lib/Zend/Cache/Backend/File.php and changed the

'cache_dir' => null,

to

'cache_dir' => 'tmp/',

Before doing it, I created folder named tmp under root of my website given IUSR writing permission.

Tuesday, July 8, 2014

Upgrading Magento Via SSH

Once you've accessed your site via SSH, change in to the directory where Magento is installed and run the following commands to upgrade Magento (you should make a backup of your files and database before proceeding):

chmod +x mage
./mage mage-setup .
./mage config-set preferred_state stable
./mage sync
./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force
php shell/indexer.php reindexall
rm -rf downloader/.cache/ var/cache/


For Magento 1.4.x and earlier, please use the following commands:
chmod +x pear
./pear upgrade-all
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/* var/cache/

If you receive an error, that means the PEAR registry has not been initialized. You need to run the following commands:

chmod 550 pear
./pear mage-setup .
./pear install magento-core/Mage_All_Latest
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/* var/cache/

Friday, May 23, 2014

Associate simple products with configurable products programmatically in Magento

This was an interesting one the other day – we had the simple products created, and we had the configurable products created, but since they’d been created separately, they weren’t associated with each other. Could we come up with a script to do just that? Turns out…yes!

The starting point is a CSV file with two columns – on the left the SKU of the simple product, and on the right the SKU of the configurable product with which it is to be associated. Don’t worry about putting in a header row – really not necessary.

That CSV then gets uploaded to the web root of the site called “skus.csv” (or whatever you want, really). The script which does the magic is nice and simple and looks like this (I’ll run through the salient points further down) :

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$file_handle = fopen("skus.csv", "r");
while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
    $simpleSku = $line_of_text[0];
    $configurableSku = $line_of_text[1];
    $simpleProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$simpleSku);
    $configurableProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$configurableSku);
    $simpleId = $simpleProduct->getId();
    $ids = $configurableProduct->getTypeInstance()->getUsedProductIds();
    $newids = array();
    foreach ( $ids as $id ) {
        $newids[$id] = 1;
    }
    $newids[$simpleId] = 1;
    echo "Updating configurable product " . $configurableSku;
    echo "<br>";
    Mage::getResourceModel('catalog/product_type_configurable')
->saveProducts($configurableProduct, array_keys($newids));
}
fclose($file_handle);
?>

The first three lines are self-evident enough if you’ve done any programming in Magento. The following lines are where the fun begins :

$file_handle = fopen("skus.csv", "r");
while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);

Let’s open the skus.csv file (or whatever you’ve called it) and then loop through its lines.

    $simpleSku = $line_of_text[0];
    $configurableSku = $line_of_text[1];
    $simpleProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$simpleSku);
    $configurableProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$configurableSku);

Let’s transfer the simple product SKU from the CSV into a variable, and likewise the configurable product SKU. Then let’s use that SKU to load both products into $simpleProduct and $configurableProduct respectively.

    $simpleId = $simpleProduct->getId();

For the simple product, all we need to get is its ID, so let’s squirrel that away in $simpleId.

For the configurable product, it’s a little more tricky. We need to ensure that we add the simple product to its associated products, not replace any existing ones. Since we’re going to be adding an array of simple products (even if that array only has one product in it) the way we do this is to get the existing simple products which are associated with the configurable product, and put them in an array, then add in the new simple product to that array.

    $ids = $configurableProduct->getTypeInstance()->getUsedProductIds();
    $newids = array();
    foreach ( $ids as $id ) {
        $newids[$id] = 1;
    }
    $newids[$simpleId] = 1;

So here we do just that. We load any existing associated products into $ids, then loop through that and transfer them into the $newids array, then add the $simpleId to the end of the $newids array.

Finally let’s have a little output so we know what’s going on :

    echo "Updating configurable product " . $configurableSku;
    echo "<br>";

And then do the actual key part – save the configurable product with the products in the $newids array as its associated simple products.

    Mage::getResourceModel('catalog/product_type_configurable')
->saveProducts($configurableProduct, array_keys($newids));

And that’s pretty much all there is to it. It should run relatively quickly, but if in doubt then run it from the command line to avoid any timeouts. You can download the complete file below, and do shout if you’ve got any questions or suggestions for improvements.