December 24, 2014

Magento how to call other block in phtml file

Magento how to call other block in phtml file

To get the block in your template, other than child block.
When you want to call the block other than specified xml child blocks.
$this->getLayout()->getBlock('block_name')->toHtml();
For example
$this->getLayout()->getBlock('top.links')->toHtml();    

December 20, 2014

Alternate to if else use switch statement


Alternate to if else use switch statement

If you execute the if else statements which multiple conditions
its go throw each condition and check with those condition is matching. For example you written if else condition
 
 if($i == 15)
 elseif($i == 25)
 elseif($i == 35)
 elseif($i == 45)
 elseif($i == 55)
 else
You want to match 45 value,while executing this above script variable matches with each if and else condition
and finally matches 45 value, so condition executed above with unmatched value then it took the execution time.

Alternative Switch statement

Suppose you are using the swithc statement for the above case. Example
 
 switch($i) {
   case 15:
     break;
   case 25:
     break;
   case 35:
     break;
   case 45:
     break;
   case 55:
     break;
 }
In this above switch statement, if the $i values was 45 then execute 45 matched values and go through the further process.

PHP error reporting


PHP error reporting

As of developer view, error reporting is more sensitive one.

There are 3 types of errors.
1) Fatal error
2) Warning error
3) Notice error

In production environment, we cant see the errors in live it appears blank page.
In this case, you want to see the server log normally for apache server which is generated in the server log file
/var/log/apache2/error.log

In terminal, you see the last few occurences error as
tail -f /var/log/apache2/error.log

While developing environment you want to see the all errors through
ini_set('display_errors', 1); /*By default its value as 0 in php.ini*/
error_reporting(-1); /*It shows all errors*/

Magento add Custom js/css in Current Theme

Add Custom JS/CSS in current theme


If you want the css and js for all the pages then you can add the code in local.xml with default handles xml tag.
 
   
     
       
         
       
       
         [css_filename.css]
       
     
   
 
[script_filename.js] - specify the script filename
[css_filename.css] - specify the css filename

For specific pages you want to add the custom css or js, then
specify the handles in local.xml and add the custom css, js xml code.

And also if want to add the custom css in specific handles,
then add the custom add code within that handles.

Modify Home Page Banner Image


Modify Banner Image


Step 1


Go to Magento admin pages through
Admin -> CMS -> Pages -> Edit home(Which mentioned in URL key)

Step 2


After click the home page which redirected to edit page.
In home edit page, go through the Content tab in left panel, click the tab.

Step 3


You see the textarea with the HTML code, in that you find the block id "home-slider".
You will change the home page banner images in the textarea.

Magento Product Collection Query


Magento product collection query

For developers, print the product collection query.

$statusEnabled = Mage_Catalog_Model_Product_Status::STATUS_ENABLED;

$collection = Mage::getModel('catalog/product')
                 ->getCollection()
                 ->addAttributeToFilter('status', 
                  $statusEnabled);
/**
 *
 * Print query
 *
 */
echo $collection->getSelect();
/**
 *or
 */
echo $collection->getSelect()->__toString();
/**
 *
 *print collection query 
 */
$Collection->printLogQuery(true);

You can then view the result query.
For developer, enable the system log settings by
System -> Configuration -> Developer -> Log Settings
see the generated log file in [magento_root_folder]/var/log/ folder

Magento Add the Default Permission for Folders


Folder permissions

/media - accessing the product images
/var - generating the cache, report files

Downloader, var and media folders are need be writable
[magento_root_folder]/var - 777 [magento_root_folder]/media - 777 [magento_root_folder]/downloader - 777

Once completed instllation and development process.
Reset back downloader folder to 755 so that this folders are non-writeable in production.

For files keep the permission as 644.

December 19, 2014

Use local.xml in theme layout for Updating Handles

Use local xml in layout file to update the handles

Step 1

Create local.xml in your custom theme as app/design/frontend/[package]/[theme]/layout/

Step 2

Create the layout code in local.xml and update the layout handles that you want in custom theme.


Within the layout tag, update the base xml handles. For example, want to remove the newsletter globally in left column for your current theme.




Magento Product Collection Filter by Dropdown Option Value

Filter product collection by option value.


Filter by option value


The product collection filter by attribute option value.

$statusEnable = Mage_Catalog_Model_Product_Status::STATUS_ENABLED;
$collection  = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => $statusEnable)
                      )                    
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('[attibute_name]', 
                        array('eq' => '[value]')
                      );
    

Filter by dropdown option value


The product collection filter by dropdown option value.

$sAttributeName = '[custom_attribute_identifier_id]'; //for example: color, size

/*
 * Get custom attribute option values
 *
 */
$optionValues = Mage::getResourceModel('catalog/product')
                ->getAttribute($sAttributeName)
                ->getSource()
                ->getAllOptions(false);

/*
 * Select the option id for the choosen dropdown option value
 *
 */
foreach($optionValues as $options) {

    if($options['label'] == '[choosen_value]') {
        $optionIds[] = $options['value'];         
    }
}

/* print_r($optionIds); */

/*
 * Filter product collection by dropdown option id
 *
 */
$collection  = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                      )                    
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter($sAttributeName, 
                        array('in' => $optionIds)
                      );
[choosen_value] In frontend, selected dropdown value to match option values to get option id.

December 17, 2014

Magento Product Collection by Attribute Filter

Add attribute to filter in product collection


The below part code shows the product collection filter by attribute.

For example
You want to filter the product collection by status enabled product,
refer the code below this do that
$collection  = Mage::getModel ('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                      );

print_r($collection);

Magento Get Options Values for Dropdown


Get dropdown option values

The dropdown value that you want to get an option values.
$sAttributeName
$sAttributeName = 'color';
$optionValues = Mage::getResourceModel('catalog/product')
                ->getAttribute($sAttributeName)
                ->getSource()
                ->getAllOptions(false);


You dont want the empty value in the option values then set the false value for first argument in below function call
getAllOptions(false)

Remove the Block in xml file


Remove the block in layout xml file

To remove the block from specific layout. You will copy the base layout file from the base folder to current theme layout folder.
In that, you will remove the block name using

And other way for removing the block by creating the local.xml in your current theme layout folder and add the block remove code there.
For example



In some cases you want to remove the child block, refer the code below to remove the child block

   


December 14, 2014

Update Multiple Products Atrributes values using UpdateAction Function

Update multiple product id attribute values


To update multiple product attribute values using simple code.
Mage::getSingleton('catalog/product_action')
   ->updateAttributes(
    $productIds, 
    array('[attribute_id]' => [attribute_value])
     );
If you want to update the attribute values for muliple products, then the above code will do the magic for that.

for ex:
Want to update the meta title for multiple products, refer the code below.
/*
$collection refers to the set of product collections
*/
$productIds = $collection->getAllIds();
/*
*print_r($productIds);
*/
Mage::getSingleton('catalog/product_action')
   ->updateAttributes(
    $productIds, 
    array('meta_title' => 'title added')
     );


How to add Additional Data in Payment Additional Data Field


Set additional data/information in payment instance

If you want to add the additional information in payment instance, then

Step1
In the Model file of your created payment
Mage_Payment_Model_Method_[custom_name]
add the below code in
assignData()
function
$this->getInfoInstance()->setAdditionalData([value to set]);

for example
$data['pay'] = 'xxxx';
$this->getInfoInstance()->setAdditionalData(serialize($data));


Step2
In Block folder, create payment info file that extends info block, add the below code in info phtml file
protected $_pay;

public function getPay()
{
     if (is_null($this->_pay)) {
        $this->_convertAdditionalData();
     }
     return $this->_pay;
}

protected function _convertAdditionalData()
{
    $this->_pay= '';

    $data = @unserialize($this->getInfo()->getAdditionalData());        
    if (is_array($data )) {
         $this->_emi = isset($data ['pay']) ? (string) $data ['pay'] : '';
    }
    return $this;
}


Step3
In the payment info phtml file, add the below code to show the additional data added.
<?php  
echo ( if($this->getPay()) ? $this->getPay() : '');  
?>


Now check the
additional_data field
in
sales_flat_order_payment
table for that order, you will find the data that added in table.

Magento how to Call cms Static Block Created in Admin

Create CMS static block


Create static block in Magento admin area. Add new block in Admin -> CMS ->Static Blocks and create new. Note down the Identifier of that block going to create.

If want to call the static block in phtml file, refer the below code to add in that

$this->getLayout()->createBlock('cms/block')->setBlockId('[identifier]')->toHtml();

[identifier] denotes the name of the static block.

You can add this code in which the block to appear.

December 05, 2014

Using Index Management in Terminal

Reindex Data using linux terminal


Reindex data through admin as

Admin -> System -> Index Management

Navigate to root folder

Using terminal as

cd [magento_root_folder]/shell

Press Enter

[magento_root_folder] - defines magento installed root folder.

List all the files in the folder

cd ls

Press Enter

View status of the all indexes

php indexer.php --status

Press Enter

You find the status of all the avaiable indexes

Reindex the catalog_product_price

php indexer.php --reindex catalog_product_price

Press Enter 

List of terminal execution indexes

By default

Name of indexes        Exceuting code path in terminal

Product Attributes     catalog_product_attribute Product Prices         catalog_product_price
Catalog Url Rewrites   catalog_url
Product Flat Data      catalog_product_flat
Category Flat Data     catalog_category_flat Category Products      catalog_category_product
Catalog Search Index   catalogsearch_fulltext
Stock status           cataloginventory_stock
Tag Summary            tag_summary 

To Indexing all the availabe indexes

php indexer.php --reindexall