Tuesday 2 July 2013

Magento increment QTY Box in Cart or View page

Untitled Document Magento had default textbox for Quantity but some time we require to add the qty box  with increment value without entering the value in textbox.We can add the followimg code in cart or view page



1) Add the one new file called jquery.qty.js and enter the following code

jQuery(document).ready(function(){  jQuery("div.quantity").append('<input type="button" value="+" id="add1" class="plus" />').prepend('<input type="button" value="-" id="minus1" class="minus" />');          jQuery(".plus").click(function()          {              var currentVal = parseInt(jQuery(this).prev(".qty").val());              if (!currentVal || currentVal=="" || currentVal == "NaN") currentVal = 1;            jQuery(this).prev(".qty").val(currentVal + 1);            });          jQuery(".minus").click(function()         {              var currentVal = parseInt(jQuery(this).next(".qty").val());              if (currentVal == "NaN") currentVal = 1;              if (currentVal > 1)              {                  jQuery(this).next(".qty").val(currentVal - 1);              }          });             });

and place as per your theme folder structure

2)Add the Following
If you want in cart page open app/design/frontend/default/yourtheme/template/catalog/prdouct/view/addtocart.phtml search for qty code and place div like this
 <div class="quantity">              <input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="2" title="<?php echo $this->__('Qty') ?>" class="input-text qty" maxlength="12" />  </div>

IF u want in view page open app/design/frontend/default/yourtheme/template/checkout/cart/item/default.phtml search for qty code and place div like this
<div class="quantity">  <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />  </div>

Just check you will get the incerement box in cart and view page    
Hope this will help you!

Magento 1.7 Configurable Product Export Fix

There is a known issue affecting both the Magento Community and Enterprise Edition export system. I have personally tested this fix on Magento Community v1.7.0.2 and Magento Enterprise v1.12.0.2, but I'm sure it will work on any version that is having the same symptoms.
The issue is with the core Import/Export functionality found in System > Import/Export > Export menu item in the Magento backend. If you have configurable products that are configurable by only 1 attribute, you won't experience difficulities. However, if you have a configurable product with multiple configurable attributes (i.e. a T-Shirt configurable by both size and color) then you will notice that your export file only contains data about one configurable attribute. This data can be found in the _super_attribute_code and _super_attribute_option columns. As in the case of my T-Shirt example, these columns would only contain data about the size attribute options, and nothing about color.
To fix this issue we must override one of Magento's core class files, at least until they come out with a newer patched version. We never touch core Magento files, so what we are going to do is replicate this file in the local code pool and make our changes there. From your root Magento install directory, copy the file
app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
to
app/code/local/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
Now, open up the Configurable.php file you just copied to the local code pool and navigate to line 223. This line should read
$attributesOptionsData[$superAttribute->getAttributeId()] = $this->_getReadAdapter()->fetchAssoc($select);
You need to change this line to read
$attributesOptionsData[$superAttribute->getAttributeId()] = $this->_getReadAdapter()->fetchAll($select);
Now, clear your cache and try the export again. You should see all your configurable attribute data in the file now. And now, my T-Shirts have both the size and color attribute associations in the export file. Once Magento fixes this issue in a later release, just remember to delete your local copy of Configurable.php.

Hide category in filter option

Untitled Document

This is what I did to remove the “Category” section from my layered navigation so I wouldnt have any repeat information with the attributes I wanted in the layered navigation.

go to app/design/frontend/default/default/template/catalog/layer and open up view.phtml for edit.

This is the code I have within the “dl” tags:

<dl id="narrow-by-list"><?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<?php if($_filter->getName() != "Category"){ ?><dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd><?php } endif; ?>
<?php endforeach; ?></dl>

All I did was add the if statement to allow everything in layered navigation except the group with the name of “Category.” I dont have Minimal Price in my nav but Im sure this would work for that too, just add it in the if statement.

Product Collection

Untitled Document
In this blog, we will see some important function in magento product collection class.

Product Collection class in magento is Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection. Lets look at the important functions

Get All Products of a category
1
2
3
$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
1
2
$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
1
2
$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
1
2
3
4
$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
1
2
3
$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
1
2
$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
1
2
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addStoreFilter();
Filter Current Website Products
1
2
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addWebsiteFilter();
Get All Products Ids
1
2
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getAllIds();

This returns an array with only products ids of collection.

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

This adds SEO friends urls to our product collection.

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

This will add category ids to the products.

Add Tier Pricing
1
2
$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.

Function in Product Object

getTypeInstance()

This is an important function in magento and used widely. This function return an object of product type class located in folder Mage_Catalog_Model_Product_Type. These classes have function specially related to their product type. For example, functions related to configurable product only are located at Mage_Catalog_Model_Product_Type_Configurable.

getIdBySku()

This functions returns the id of a product based on its sku. This is usually used, when you want to load a product, but you only have its sku.

There are many more functions in both class which you should go through and are very useful. These function saves a lot of time, than to write complex sql query.
- See more at: http://www.excellencemagentoblog.com/magento-product-collection#sthash.tO9L2q6b.dpuf

17 useful functions for manipulating arrays in PHP.

Like arrays in other languages, PHP arrays allow you to store multiple values in a single variable and operate on them as a set. PHP offers an extensive array manipulation toolkit—over 60 functions—that lets you process arrays in almost any way imaginable including reversing them, extracting subsets, comparing and sorting, recursively processing, and searching them for specific values.
This document outlines some of the more useful functions in the PHP array toolkit, with explanations and usage examples:

This table is also available as free downloadable PDF.



Function
Explanation
Example
sizeof($arr)
This function returns the number of elements in an array.
Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array.
Code:
$data = array("red", "green", "blue");

echo "Array has " . sizeof($data) . " elements";
?>

Output:
Array has 3 elements
array_values($arr)
This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>

Output:
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>

Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr)
This function removes an element from the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
This function adds an element to the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
This function removes an element from the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
while (list($key, $value) = each($data)) {
echo "$key: $value \n";
}
?>

Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Code:
$data = array("g", "t", "a", "s");
sort($data);
print_r($data);
?>

Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns.
Code:
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>

Output:
Array
(
[apple] => a
[ball] => b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values.
Code:
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>

Output:
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.
Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries.
Code:
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>

Output:
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list.
Code:
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>

Output:
Today's color is red
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the matching index.
Code:
$data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>

Output:
Found blue
array_slice($arr, $offset, $length)
This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.
Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data.
Code:
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>

Output:
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key.
Code:
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>

Output:
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func)
This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.
Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%.
Code:
function reduceBy10(&$val, $key) {
$val -= $val * 0.1;
}

$data = array(10,20,30,40);
array_walk($data, 'reduceBy10');
print_r($data);
?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)

Magento: Show Billing-Shipping Address in Customer Signup-Registration page

Untitled Document

Here are some ways (2 ways below) to show customer address information in registration page.

When you fill up the address fields and signup then both your billing and shipping addresses are filled up.

Here is how to enable address fields in signup page:-

1) First way [EASY]

- Open template/customer/form/register.phtml
- Just above this line:

<?php if($this->getShowAddressFields()): ?>

Write this line:

<?php $this->setShowAddressFields(true); ?>

- So, the code should look like this:

<?php $this->setShowAddressFields(true); ?>
<?php if($this->getShowAddressFields()): ?>

2) Second way [STANDARD]

- Open layout/customer.xml
- Add this line inside customer_account_create node:

<action method="setShowAddressFields"><value>true</value></action>

- So, the xml code will look like this:

<customer_account_create translate="label">
<label>Customer Account Registration Form</label>
<!-- Mage_Customer -->
<remove name="right"/>
<remove name="left"/>
 
<reference name="root">
    <action method="setTemplate"><template>page/1column.phtml</template></action>
</reference>
<reference name="content">
    <block type="customer/form_register" name="customer_form_register" template="customer/form/register.phtml">
        <action method="setShowAddressFields"><value>true</value></action>
        <block type="page/html_wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
            <label>Form Fields Before</label>
        </block>
    </block>
</reference>
</customer_account_create>

You should be able to show customer address fields on registration by using any of the above two methods.

Hope it helps. Thanks.

- See more at: http://blog.chapagain.com.np/magento-show-billing-shipping-address-in-customer-signup-registration-page/#sthash.BFFDfdMK.dpuf

Tuesday 7 May 2013

Customize Magento’s Image Resize Functionality

Untitled Document

Need to remove the white border around your images? Don't want everything to be square? Here is how to customize the ->resize functionality in Magento. Here is what the default image resize code looks like:

<?php echo $this->helper('catalog/image')->init($_product, 'image')->resize(350) ?>

The problem is this will always give you a 350 x 350 pixel square. If your image is rectangular, you will get a white frame around it to make it square. The resize() command can be quickly and easily customized to work better with rectangular images.

->constrainOnly(true) This will not resize an image that is smaller than the dimensions inside the resize() part.

->keepAspectRatio(true) This will not distort the height/width of the image.

->keepFrame(false) This will not put a white frame around your image.

Here is what your image code would look like with all these set:

<?php echo $this->helper('catalog/image')->init($_product, 'image')->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->resize(350, null) ?>

This would resize your images to a max 350 width and constrain the height. If your image is taller than it is wide, you will end up with a nicely resized vertical image.

Here are the various places that images are used:

/app/design/frontend/default/yourtheme/catalog/product/view/media.phtml  (displays the image on your product view page)
/app/design/frontend/default/yourtheme/catalog/product/list.phtml  (displays the image on category view)

This has helped us out many times. Let us know in the comments if you use it!