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



November 26, 2014

Apache service Start, Stop and Restart

To start Apache server
sudo service apache2 start
           ( or )
sudo /etc/init.d/apache2 start


 To stop Apache server
sudo service apache2 stop
           (or)
sudo /etc/init.d/apache2 stop

 To restart Apache server
sudo service apache2 restart
           (or)
sudo /etc/init.d/apache2 restart

MySQL service Start, Stop and Restart

MySQL service

To start MySQL server
sudo service mysql start
           ( or )
sudo /etc/init.d/mysql start

 To stop MySQL server
sudo service mysql stop
           (or)
sudo /etc/init.d/mysql stop

 To restart MySQL server
sudo service mysql restart
           (or)
sudo /etc/init.d/mysql restart




November 25, 2014

Find the Array key in Nested Array

In nested array find the array key for matched value

function recursive_array_search($needle, $haystack) {
    foreach($haystack as $key=>$value) {
        $current_key = $key;
        if($needle === $value
  || (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
 
Find the key of the matched element in nested array.

$needle
- String which has to find.

$haystack
- Array elements $needle has to search in this array.

PHP MySQL Connection

MySQLI Connection - I for Improved

Connect the database from php throug MySQLI
 
/*hostname - localhost, user - user, password - null, database - test*/

$db = new mysqli('localhost', 'user', '', 'test');

if($db->connect_errno > 0){
    die('Error in connecting database (' . $db->connect_error . ')');
}

Now doing the simple query to get records from employee table
 
/* Do Query */

$sql = "SELECT * FROM `employee`;

if(!$result = $db->query($sql)){
    die('Query error ' . $db->error);
}

Display the output by fethcing the table records
 
/* Fetching records */

while($row = $result->fetch_assoc()){
    echo $row['username'];
}

Magento Display Categories and Subcategories


Display categories and subcategories in Magento page

    /*Display current store categories*/

    $_helper = Mage::helper('catalog/category');
    $_categories = $_helper->getStoreCategories();

    /*Parent categories*/

    foreach($_categories as $_category) {

      if(!$_category->getIsActive()){
        continue;
      }

      echo $_category->getName();
      echo render_child($_category->getId());
    }
    
    /*Render child categories*/

    function render_child($cid) {
 
     $html = '';
     $_subCategory = Mage::getModel('catalog/category')->load($cid);

     $_subCategories = $_subCategory->getChildrenCategories();

     if (count($_subCategories) > 0){

       $html .= '<ul>';

       foreach($_subCategories as $_subCat){

         if(!$_subCat->getIsActive()){
           continue;
         }
    
         $html .= '<li>';
 
         /*Display first level sub categories*/

         $catUrl = Mage::helper('catalog/category')
                            ->getCategoryUrl($_subCat);

         $html .= "<a href='".$catUrl."'>".$_subCat->getName()."</a>";
  
         /*Display first level sub categories*/

         /*If needed display next level sub categories*/

         $html .= render_child($_subCat->getId()); 
  
         /*If needed display next level sub categories*/

         $html .= '</li>';
      }
   
      $html .= '</ul>';
     }  
     return $html;
  }


Displaying the category and subcategories from the current store. After getting the store categories, check the category is active and output the parent category name.

With the help of
 render_child 
function, check the active subcategories then display first level child elements in list format.

Would like to display all subcategories then call
 render_child 
function, with argument as current category id.
    

Magento List Categories and Subcategories which has Include in Navigation Menu as yes


List all categories and subcategories which has Include in Navigation Menu as yes

$collection = Mage::getResourceModel('catalog/category_collection')
    //only active categories
    ->addAttributeToFilter('is_active', 1) 
    //categories included in menu
    ->addAttributeToFilter('include_in_menu', 1) 
    ->addAttributeToSelect('*');

foreach ($collection as $category) {
    //do something with $category

     echo $category->getSku();
}

November 21, 2014

Magento Debugging Log Files

Create log file


In developing magento module its necessary to know how to log the file.
If you want to log the variables in object, array and strings.

Refer the code below to log the variable.

Mage::log($myVariable, NULL, '[nameOfFile].log');

This log file will create in magento log folder i.e [magento_root_path]/var/log

Magento Template Hints

 

Magento Template and Block Hints


In Magento Admin, look into developer option in left side bottom under System -> Configuration.

Choose the website or store you would like to see the template hints by

Enabling the template hint path and block path

This give the Block class name and corresponding template file which it displays output.

Get a Configurable Products Associated or Related Simple Product

Output the configurable related products.

/* Get all products */

$collection  = Mage::getModel ('catalog/product')
                 ->getCollection(); 

foreach($collection as $product) {
   
   /* If product is not configurable move to next item in loop */

   if($product->getTypeId() != "configurable"):
 continue;
   endif;

   /* Assign configurable related products in collection  */

   $conf = Mage::getModel('catalog/product_type_configurable')
        ->setProduct($product);


   $simpleCollection = $conf->getUsedProductCollection()
    ->addAttributeToSelect('*')    
    ->addFilterByRequiredOptions();

   /* Get all configurable related product ids */

   $simpleIds = $simpleCollection->getAllIds();

   /* Loop all related products and output the product name */

   foreach($simpleCollection as $simpleProduct){
      echo $simpleProduct->getName(). "<br/>";
   }
}

November 10, 2014

What happen when Browser Cookie will Removed, Session retains as its ?


When webpage was loaded, unique session id will generated and that stored in cookie. If cookie will removed then session cant retain.

PHP Session and Cookie


The main difference between sessions and cookies is that cookies are stored in the user's browsers, and session are stored in server.

A cookie is small file that store in user's computer. Cookie data expiry depend on expiration date where session retain until browser run.

PHP List of array sort functions

sort().

rsort().

natsort().

natcasesort().

ksort().

krsort(). 

asort().

arsort().


Use of array_map Function in Real Time ?

It will apply for many things. For example want to do php function for set of elements will use that
Example

If have like below

$first_name = trim($_POST['firstname']);


$lastname = trim($_POST['lastname']);

but instead of above

$_POST = array_map("trim", $_POST);


$array = array_map("trim", $array);


It will remove the spaces for the set of elements.



How to Add the Element to the array First & Last, how to remove the same ?


array_push - Adding elemen to the last

array_unshift - First element to prepend

array_pop - Remove the first element of the array

array_shift - Remove the last element

How to determine PHP version in Servers ?

PHPINFO gives various detail scripting running system, Apache built-in modules, PHP working directory, PHP modules, PERL information and third party system information that are used in server.

phpinfo();

Type of Magento Sessions

Core/Session:

Mage::getSingelton('core/session')

Handles information about end user ip address, messages, cookies

Customer/Session:

Mage::getSingleton('customer/session')

Handles information about the customer.

Checkout/Session:

Mage::getSingleton('checkout/session')

Handles information about the checkout, cart and details of guest account user 

October 28, 2014

Magento Interview Questions


Getting order id for new order


Magento get new order id based on "eav_entity_store" table

PHP Interview Questions


Echo vs print.


echo() and print() are language constructs in PHP, both are used to output strings.

echo() can take multiple expressions whereas print cannot take multiple expressions.

August 07, 2014

Magneto create admin user progrmatically

### Create New admin User programmatically. ####
require_once('./app/Mage.php');
umask(0);
Mage::app();

try {
 $user = Mage::getModel('admin/user')
           ->setData(array(
                'username' => '[user_name]',
                'firstname' => 'Admin',
                'lastname' => 'Admin',
                'email'  => '[user_email]',
                'password' => 'admin123',
                'is_active' => 1
               ))->save();

} catch (Exception $e) {
 echo $e->getMessage();
 exit;
}

//Assign Role Id
try {
       //Administrator role id is 1 ,Here you can assign other roles

     $user->setRoleIds(array(1))  
          ->setRoleUserId($user->getUserId())
          ->saveRelations();

} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}

echo 'Admin user created successfully';