PHP SOLUTIONS

This is the blog for getting Idea regarding PHP, Magento, jQuery and JavaScript for Customization.

Monday 31 December 2012

Magento : Change price in cart programatically

Hi,

  Here for change the product price into cart programatically

  There is an simple way for change this product price and add custom price for the specific product into cart when add the product into cart in magento.

1) Create an Attribute for the products,

   Suppose an Ex. is Change Price
   Set its type yes/no for the product

2) Open File, code/core/mage/checkout/model/cart.php

3) Goto on this function,

     public function save()
    {
      ........
      ........
     }

4) Copy and Paste below code,

    public function save()
    {
        Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
              
        foreach($this->getQuote()->getAllItems() as $item) {            
          $productId = $item->getProductId();
          $product = Mage::getModel('catalog/product')->load($productId);
          if($product->getAttributeText('change_price') == 'Yes')
         {
                 $price = 5;
                 $item->setCustomPrice($price);
                 $item->setOriginalCustomPrice($price);
          }
        } 
        $this->getQuote()->save();
        $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
       
        /**
         * Cart save usually called after changes with cart items.
         */
        Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
        return $this;
      }

5) Now, Insert Product form Admin and set its Change Price value yes for that product,

6) Add that product to cart you can see that, product Unit price will change to $5.

   This is work for me in 1.7.0.2

 Enjoy!!!!!

Monday 24 December 2012

Magento : Get custom options on category page

 Here, The Code for get Custom Options of Products on category Page, This is useful for reduce the time for customer purchase product and add to cart it, there is another methods are also but in that we can't add product with it's custom options, so using this we can add product to cart with its custom options.


 <?php
    $sandy = "";
    $attVal = $product->getOptions();
    if(sizeof($attVal))
    {
          foreach($attVal as $optionVal)
          {   
        $type = $optionVal->getType();
        if($type != 'field' && $type != 'file' )
         {
                $sandy .= $optionVal->getTitle().": ";
                $sandy .= "<select id='select_".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
                foreach($optionVal->getValues() as $valuesKey => $valuesVal)
            {           
                if($valuesVal->getPrice() != "0.00000")
                {
                      $sandy .= "<option price='".$valuesVal->getPrice(true)."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle() .'+'.  $valuesVal->getPrice(true) ."</option>";       
                  }
                  else
                  {
                $sandy .=  "<option price='".$valuesVal->getPrice(true)."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle() ."</option>";
                }
            }
            $sandy .= "</select>";
        }
        else if($type == 'file')
        {
            $sandy .= $optionVal->getTitle().": ";
                $sandy .= "<input type='file' name='options_".$optionVal->getId()."_file'>";               
              }
        else
        {
            $sandy .= $optionVal->getTitle() ."  : ";
                $sandy .= "<input type='text' name='options[".$optionVal->getId()."]' id='options_".$optionVal->getId()."_text' onchange='javascript: getval();'>";                  
        }
        }
    }
    echo $sandy;
  ?>

  <?php echo $this->getPriceHtml($_product, true) ?>
    
  <?php if(!$_product->isGrouped()): ?>
  <label>Qty:</label>
        <input type="text" id="qty_main" maxlength="12" value="<?php echo $this->getMinimalQty($_product)==null?1:$this->getMinimalQty($_product) ?>" onblur="calculatetotal();"/>
        <button type="submit" id="addtocartbt_<?php echo $_product->getSku(); ?>" onclick="productAddToCartForm<?php echo $_product->getId() ?>.submit()">Add to Cart</button>
  <?php endif; ?>  
  </div>
                                        
  </form>
      
<script type="text/javascript">
       
var productAddToCartForm<?php echo $_product->getId() ?> = new VarienForm('product_addtocart_form_<?php echo $_product->getId() ?>');                       
    productAddToCartForm<?php echo $_product->getId() ?>.submit = function()
    {
            if (this.validator.validate())
        {   
            this.form.submit();                           
            }                   
        }.bind(productAddToCartForm<?php echo $_product->getId() ?>);
  </script>
  <?php else: ?>
      <div class="out-of-stock"><?php echo $this->__('Out of stock') ?></div>
  <?php endif; ?>

Wednesday 28 November 2012

Magento : Remove TAX / VAT from grand total in checkout


Here, We can Remove Tax from Grand Total.

If we want to removed tax for all customer we simply remove Tax class from the produc's then It will remove automatically.

But If you want to remove Tax for specific customer you can do using below steps.

Here Example for Remove Tax for that Customer Who have their Business VAT Numbers.

1) Goto " app/code/core/mage/tax/model/calculation.php  "

2) Find this Function "  public function getRateRequest() "

3) You can get this at the end of the function

    $request = new Varien_Object();
        $request
            ->setCountryId($address->getCountryId())
            ->setRegionId($address->getRegionId())
            ->setPostcode($address->getPostcode())
            ->setStore($store);
            ->setCustomerClassId($customerTaxClass);

4) Now Here for who have VAT/TAX numbers, no apply Tax in Grand Total

    $eutax = $customer['taxvat'];

    if($eutax != '')
   {
            //Who have to insert their VAT Number then remove TAX from Grand Total
            $request = new Varien_Object();
            $request
                       ->setCountryId($address->getCountryId())
                       ->setRegionId($address->getRegionId())
                       ->setPostcode($address->getPostcode())
                       ->setStore($store);                      
    }
    else
    {
           //Who have to not insertd their VAT Number then add TAX in Grand Total
           $request = new Varien_Object();
           $request
                      ->setCountryId($address->getCountryId())
                      ->setRegionId($address->getRegionId())
                      ->setPostcode($address->getPostcode())
                      ->setStore($store);
                      ->setCustomerClassId($customerTaxClass);


    }

5) Now check Tax is Remove from Grand Total in checkout.


Saturday 24 November 2012

Magento : Upgrade Magento version



You can do this for Upgrade Magento 1.4 to 1.7

Do this in your Local Machine because when you Upgrade Do not reload page before complete all steps

1) Backup your current Site files and Database

2) Download Newer version from http://www.magentocommerce.com/download
    then Extract that zip in Directory

3) Upload or Override newer version files on your current site files

4) your database upgrade automatically so don't do any thing with that

5) After Complete override then remove site cache and index from admin

6) Now, Reload your site, you can see Upgraded version 1.7 in footer


Saturday 17 November 2012

Magento : Add JavaScript / CSS



There is Two way for add external Javascript in magento

1) Using Page.xml
2) Using Head.phtml


1) Using Page.xml :::\\//

<action method="addJs"><script>directoryname/javascript_name.js</script></action>


2) Using Head.phtml :::\\//

<script type="text/javascript" src="<?php echo $this->getSkinUrl('directoryname/javascript_name.js') ?>"></script>

<link href='<?php echo $this->getSkinUrl('directoryname/css_name.css')  ?>' rel='stylesheet' type='text/css' />

Magento : Get popular tags list for any page


Here, I get Popular Tags List on Any page,

Using this can get HTML Layout of the Phtml page

Simply, Copy and Paste below code


<?php echo $this->getLayout()->createBlock('tag/popular')->setTemplate('tag/popular.phtml')->toHtml(); ?>


If you want another page html then change block directory and type,

also replace template name of phtml file.

Friday 2 November 2012

Magento : Get Product Ids, Sku, Category Id in Custom Module Field set




A) Open your Form.php File  "app\code\local\[Namespace]\[Module Name]\Block\Adminhtml\[Modele Name]\Edit\Tab\Form.php"




/* Three functions for call Category list, Product_ids and Product Skus */

 <?php

              class Addon_Beautygirl_Block_Adminhtml_Beautygirl_Edit_Tab_Form extends            Mage_Adminhtml_Block_Widget_Form

  {

        public function buildCategoriesMultiselectValues(Varien_Data_Tree_Node $node, $values, $level = 0)
       {
               $level++;
               //-----new start for only 3 level category
               if($level>3)
               {
                         return $values;
                         // print_r($values);
                }
                //-----new close
                $values[$node->getId()]['value'] =  $node->getId();
                $values[$node->getId()]['label'] = str_repeat("---", $level) . $node->getName();

                foreach ($node->getChildren() as $child)
                {
                       $values = $this->buildCategoriesMultiselectValues($child, $values, $level);
                 }
                 return $values;
       }

       public function load_tree()
      {
                $tree = Mage::getResourceSingleton('catalog/category_tree')->load();
                $store = 1;
                $parentId = 1;
                $tree = Mage::getResourceSingleton('catalog/category_tree')->load();
                $root = $tree->getNodeById($parentId);
                 if($root && $root->getId() == 1)
                 {
                         $root->setName(Mage::helper('catalog')->__('Root'));
                  }
                  $collection = Mage::getModel('catalog/category')->getCollection()
                                       ->setStoreId($store)
                                       ->addAttributeToSelect('name')
                                       ->addAttributeToSelect('is_active');
                  $tree->addCollectionData($collection, true);
                  return $this->buildCategoriesMultiselectValues($root, array());
         }

         function getProductCollection()
         {
                 $model = Mage::getModel('catalog/product'); //getting product model
                 $collection = $model->getCollection(); //products collection
                 $count = 0;
                 foreach ($collection as $product) //loop for getting products
                {
                        $a = $count++;
                        $values[$a]['label'] = $product->getId();
                        $values[$a]['value'] = $product->getId();
                        //$pids[] = $product->getId();
                        //return $product->getSku();
                  }
                  //print_r($pids);
                  return $values;
           }

        function getProductCollectionskus()
       {
                 $model = Mage::getModel('catalog/product'); //getting product model
                 $collection = $model->getCollection(); //products collection
                 $count = 0;
                 foreach ($collection as $product) //loop for getting products
                 {
                         $a = $count++;
                         $values[$a]['label'] = $product->getSku();
                         $values[$a]['value'] = $product->getSku();
                 }
                 //print_r($pids);
                 return $values;
        }




  protected function _prepareForm()
  {
      $form = new Varien_Data_Form();
      $this->setForm($form);
      $fieldset = $form->addFieldset('beautygirl_form', array('legend'=>Mage::helper('beautygirl')->__('Item information')));
   
      $fieldset->addField('title', 'text', array(
          'label'     => Mage::helper('beautygirl')->__('Title'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
      ));

 $fieldset->addField('status', 'select', array(
          'label'     => Mage::helper('beautygirl')->__('Status'),
          'name'      => 'status',
          'values'    => array(
                              array(
                              'value'     => 1,
                              'label'      => Mage::helper('beautygirl')->__('Enabled'),
                               ),
                             array(
                             'value'     => 2,
                             'label'     => Mage::helper('beautygirl')->__('Disabled'),
                              ),
                              ),
         ));

    $fieldset->addField('filename', 'file', array(
          'label'     => Mage::helper('beautygirl')->__('File'),
          'required'  => true,
          'name'      => 'filename',
 ));

/* This Variable's Contain that Function's Values */

 $pids = $this->getProductCollection();
 $skus = $this->getProductCollectionskus();
 $categories_values = $this->load_tree();

 $field set->addField('girloneproductid', 'multiselect', array(
                'name' => 'girloneproductid',
                'label' => Mage::helper('beautygirl')->__('Select Product ID'), 
                'required' => true ,
                'values' => $pids,
));

 $fieldset->addField('girloneproductsku', 'multiselect', array(
                'name' => 'girloneproductsku',
                'label' => Mage::helper('beautygirl')->__('Select Product SKU'), 
                'required' => false ,
                'values' => $skus,
));

$fieldset->addField('girlonecategoryid', 'multiselect', array(
                'name' => 'girlonecategoryid',
                'label' => Mage::helper('beautygirl')->__('Select Category'), 
                'required' => false ,
                'values' => $categories_values,
));

Wednesday 31 October 2012

Magento : get CMS static block using XML file


A) Create one Static Block in CMS > Static block Admin

       1.  Block Title =  heders_links
       2.  Identifier    =  heders_links
       3.  Status        =  Enable
       4.  Content     =  "Give your Custom Design Layout"
             ex.
            <ul class="header-menu">
                     <li><a href="{{store direct_url=''}}">Home</a></li>
                     <li><a href="{{store direct_url='about-magento-demo-store'}}">About Us</a></li>
                     <li><a href="{{store direct_url='catalogsearch/advanced/'}}">Advanced Search</a></li>
                     <li><a href="{{store direct_url='contacts/'}}">Contact Us</a></li>
            </ul>


B)  Copy code inside page.xml file


     <block type="cms/block" name="header_links">
                    <!--
                        The content of this block is taken from the database by its block_id.
                        You can manage it in admin CMS -> Static Blocks
                     -->
                    <action method="setBlockId"><block_id>header_links</block_id></action>
            </block>

Tuesday 30 October 2012

Magento : get category list on Home page


Actually There are various types to get category List but I suggest two way for this,

1) First One

Simply follow bellow steps to get Category List on Home page,

A) Create a one Phtml file inside

     app/design/frontend/base/default/template/catalog/navigation/

     use file name left_navcategory.phtml

B) Now, Copy below code and paste in left_navcategory.phtml

   <?php
if(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms') :
?>

<?php
$obj = new Mage_Catalog_Block_Navigation();
$store_cats    = $obj->getStoreCategories();
$current_cat     = $obj->getCurrentCategory();
$current_cat    = (is_object($current_cat) ? $current_cat->getName() : '');

foreach ($store_cats as $cat) {
    if ($cat->getName() == $current_cat) {
        echo '<li class="current"><a href="'.$this->getCategoryUrl($cat).'">'.$cat->getName()."</a>\n<ul  id='nav_category' class='nav_category'>\n";
        foreach ($obj->getCurrentChildCategories() as $subcat) {
            echo '<li><a href="'.$this->getCategoryUrl($subcat).'">'.$subcat->getName()."</a></li>\n";
        }
        echo "</ul>\n</li>\n";
    } else {
        echo '<li><a href="'.$this->getCategoryUrl($cat).'">'.$cat->getName()."</a></li>\n";
    }
}
endif ?>


C) Create one Block for that in Catalog.xml under

<reference name="left">
   <block type="catalog/navigation" name="catalog.left_navcategory" template="catalog/navigation/left_navcategory.phtml" />
</reference>



Magento : Create featured product


There is easy few steps to create Featured Product,

A) First Create a One Attribute :

    Set this under "Property Teb" of Right side, 

         1.  Attribute Code *                                        =      featured
         2. Scope                                                         =      Store View
         3. Catalog Input Type for Store Owner            =      Yes/No

  Set this under "Manage Label/Options Teb" of Right side, 

        1.  Admin                        =    Featured Product
        2.   Default Store View    =    Featured Product 


B) Now goto Catalog > Attribute > Manage Attribute Set

    1. Click on Default Attribute set,
    2. Here, see your  fetured attribute under Unassigned Attributes,  Drag that attribute inside Groups  general  directory
    3. Save



Monday 29 October 2012

Magento : Get logged customers details

There are two type

A) To get Specific Details of customer


<?php

          if(Mage::getSingleton('customer/session')->isLoggedIn())
          {
                   /* If Customer Log In to System */

                   echo $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getId());

                  echo $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());

          } 
          else
         {
                   /* If Customer not Log In to System */
                   echo "Not Log In";
         }

 ?>

B) To get all Session Details of customer


<?php

          if(Mage::getSingleton('customer/session')->isLoggedIn())
          {
                   /* If Customer Log In to System */

                   $customer = Mage::getSingleton('customer/session')->getCustomer();
   print_r($customer);
   echo $taxVat = $customer->getData('taxvat');
          } 
          else
         {
                   /* If Customer not Log In to System */

                   echo "Not Log In";
         }

 ?>

Friday 26 October 2012

Magento : Get value of CMS Static Block using XML file



This is a XML block, Simply use this in your XML file of layout directory,


<block type="cms/block" name="Here Id of your Static block">
<!--
The content of this block is taken from the database by its block_id.
You can manage it in admin CMS -> Static Blocks
-->
<action method="setBlockId"><block_id>"Here Id of your Static block"</block_id>                                 </action>
</block>


For Example,


<block type="cms/block" name="header_block">
<action method="setBlockId"><block_id>"header_block"</block_id>                                 </action>
</block>

As per example, Here "header_block" is a static block in CMS->Static Block .

Monday 15 October 2012

Magento : Set Google Translator


<!-- Put this code in Header File -->
<!-- File Path ::=> app/design/frontend/base/default/template/page/html/header.phtml-->


 <div id="google_translate_element"></div>
<script>
         function googleTranslateElementInit()
        {
new google.translate.TranslateElement({
      pageLanguage: 'en'
}, 'google_translate_element');
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Thursday 27 September 2012

jQuery : Drag and Drop


To, Drag and Drop Image, Div etc. using Jquery !


A) Attach This two JS File into your Page.

      1) http://code.jquery.com/jquery-1.7.2.min.js
      2) https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js

B) Put this Script in you page at bottom

<script type="text/javascript">

jQuery(document).ready(function(){


jQuery(".product img").draggable({

        /* Use that Class or Tag Reference using JQUERY which you want to drag [change  .product img  as per Requirement] */

containment: 'document',
opacity: 0.6,
revert: 'invalid',
helper: 'clone',
zIndex: 100

});

jQuery("div#slider4").droppable({

        /* Use the Class or Tag Reference using JQUERY where you want to drop draggable thing [change  div#slider4  as                                          per Requirement] */
drop:
function(e, ui)
{

var param = jQuery(ui.draggable).attr('src');
var params = jQuery(ui.draggable).attr('name');
var href = jQuery(ui.draggable).attr('title');

if(jQuery.browser.msie && jQuery.browser.version=='6.0')
{
param = jQuery(ui.draggable).attr('style').match(/src=\"([^\"]+)\"/);
param = param[1];
}
addlist(param,params,href);
}

});
});

function addlist(param,params,href)
{
jQuery.ajax({
type: "POST",
data: 'img='+param+'&id='+params,
url: "<?php echo Mage::getBaseUrl().'ajax/index/getdata1' ?>",
dataType: 'json',
beforeSend: function(x){jQuery('#ajax-loader').css('visibility','visible'); },
success: function(msg){

var ids = msg.id;
jQuery('#list_item').append(msg.txt);

});
}
}

,

Tuesday 25 September 2012

Magento : Get product custom option in Category page


To Get Product Custom Option On the Category page.


 <?php $i=0; foreach ($_productCollection as $_product): ?>


 <?php if($_product->isSaleable()): ?>

 <?php

                    Mage::app('base');
                    $product = Mage::getModel('catalog/product')->load($_product->getId());
    echo $product->getId();
                    $options = $product->getOptions();
                    foreach ($options as $option) {

                        foreach($option->getValues() as $value) {

                            echo $value->getOptionTypeId() . "<br/>";
                            echo $value->getTitle() . "<br/>";
                            echo $value->getPrice(true) . "<br/>";

                        }
                    }
                    ?>
               
<?php endif; ?>

<?php endforeach; ?>

Magento : Share product page Link on Facebook or Twitter



A) For ::: Face Book 


<a href="http://www.facebook.com/sharer.php?u=<?php echo $_product->getProductUrl()  ?>&t=Check+this+out" target="_blank" title="Share on Facebook"><img src="<?php echo $this->getSkinUrl()."images/icon-f.png" ?>" alt="Share on Facebook"></a>

B) For ::: Twitter
                       
<a title="Send this page to Twitter!" href="http://twitter.com/home?status=Check out the <?php echo $this->htmlEscape($_product->getName()) ?> at <?php echo $_product->getProductUrl()  ?> @foodoAU" target="_blank"><img src="<?php echo $this->getSkinUrl()."images/icon-t.png" ?>" alt="Follow foodoAU on Twitter"/></a>

Monday 24 September 2012

Magento : Check current Page is Category page OR Product page

 Here, Determine Product Page [Product Details page] And  Category Page [List Page] and Home Page

<?php

            $this->getRequest()->getControllerName();

            if($this->getRequest()->getControllerName()=='product')
             {
                    //This is Determine Product Details page.
                   //do something
             }
            if($this->getRequest()->getControllerName()=='category')
            {
                   //This is Determine List page.
                 //do others
            }

?>


<?php
      
         if(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  &&
Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' ) : 

              //This is Determine Home page.
                 //do others

      endif;

?>



Friday 7 September 2012

jQuery : Set tool-tips on Image mouse over


/* If you want to use this for multiple images change only id names */


<img id="ps_img_btn" src='<?php echo "Path of Image";?>' />
     
 <div id="ps_img_bnt_tooltip" style="display: none; position: absolute; left: 80px; top: 91px;"><p>Slim Fit. Suited for slim or athletic builds who want to show off silhouette of body.</p></div>

<script>      
            Event.observe('ps_img_btn','mouseover',function(event){        
                       $('ps_img_bnt_tooltip').style.display='block';
                       $('ps_img_bnt_tooltip').style.position='absolute';
                      /* If you want to change of Height and Width then Change Here X and Y */
                       x = 80;
                       y = 75;
                       $('ps_img_bnt_tooltip').style.left= x+"px";
                       $('ps_img_bnt_tooltip').style.top = y + "px";    })
                        Event.observe('ps_img_btn','mouseout',function(event){
$('ps_img_bnt_tooltip').style.display='none';    })
        </script>

,

Thursday 6 September 2012

Magento : Add Video to products



Here, I think you have the jQuery Javascript library installed and have "jQuery.noConflict()"' set up.  If you don't have jQuery.noConflict(), then simply replace instances of "jQuery" with "$".  If you don't have this library, download jQuery here.
Create a product attribute for the video code
Obtain and upload a copy of the free JWPlayer
Add video to a product using HTML embed code or using an FLV file

(A). Create a product attribute for the video code.
Navigate to Catalog > Attributes > Manage Attributes. Click on the "Add New Attribute" .The first tab that's open is the *Properties* tab. You are presented with lots of textboxes and dropdowns.
Attribute Properties
- Attribute Code: video
- Scope: Global
- Catalog Input Type of Store Owner: Text Area
- Default Value: [leave blank]
- Input Validation for Store Owner: None
Click the "Save Attribute" button to save the attribute.

(B). Assign the newly created attribute to an attribute set (likely Default)
While still in the Admin Panel, navigate to Catalog > Attributes > Manage Attribute Sets. From the right-hand column, labeled "Unassigned Attributes", drag our new video attribute to the "General" group found in the middle column.
Click "Save Attribute Set" button to save the attribute set.
(C). Modify the template files

c1=>. video.phtml
Create a video.phtml file with these:
<?php
$_product = $this->getProduct();
?>
<?php if( $video = $_product->getVideo() ){ ?>
<h2>Product Video</h2>
<div class="products">
<?php if( file_exists( getcwd() .'/skin/frontend/[your-package]/[your-theme]/videos/'. $video ) ){ ?>
<div id="mediaspace"> </div>
<script>
jQuery( document ).ready( function(){
jQuery.getScript( '<?php echo $this->getSkinUrl('videos/mediaplayer/swfobject.js'); ?>', function(){
var so = new SWFObject('/skin/frontend/[your-package]/[your-theme]/videos/mediaplayer/player.swf','ply','470','320','9','#ffffff');
so.addParam('allowfullscreen','true');
so.addParam('allowscriptaccess','always');
so.addParam('wmode','opaque');
so.addVariable('file','<?php echo Mage::getBaseUrl(); ?>/skin/frontend/[your-package]/[your-theme]/videos/<?php echo $video; ?>');
so.write('mediaspace');
} );
} );
</script>
<?php } else { ?>
<?php echo $video; ?>
<?php } ?>
</div>
<?php } ?>
And save the file as /app/design/frontend/[your-package]/[your-theme]/template/catalog/product/view/video.phtml
c2=>. catalog.xml
Open up /app/design/frontend/[your-package]/[your-theme]/layout/catalog.xml and add this line:
<block type="catalog/product_view" name="product_video" as="product_video" template="catalog/product/view/video.phtml"/>
as a child anywhere inside this node:
<block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">
... and save the file.
c3=>. catalog/product/view.phtml
Open up /app/design/frontend/[your-package]/[your-theme]/catalog/product/view.phtml and add this line:
<?php echo $this->getChildHtml('product_video'); ?>
wherever you want the video to appear on the page. Save the file.

(D). Obtain and upload a copy of the free JWPlayer

Download the JWPlayer from: http://www.longtailvideo.com/players/jw-flv-player/
After you download the ZIP file, extract and upload the files using an FTP client to: /skin/frontend/[your-package]/[your-theme]/videos/*
With the FTP client, rename the "mediaplayer-viral" folder to "mediaplayer"

(E). Add video to a product

In the Magento Admin Panel, navigate to Catalog > Manage Products and click on the product you'd like to add video to. You should see a textarea labeled "Video".
e1=>. Use HTML embed code
In the "Video" textarea, simply drop in the HTML code you've received (such as from YouTube) and click "Save" to save the product.
e2=>. OR use an FLV file
- Upload your FLV file to /skin/frontend/[your-package]/[your-theme]/videos/
- In the "Video" textarea, specify the filename of the FLV you've just uploaded.
Repeat Step 5 for all of the products you want to add video to.
Congratulations, you've added video to your products.
* This method is tested and working for Magento v 1.3.2.4 and 1.7.0.2

Wednesday 5 September 2012

Magento : Add tabs in custom module in magento admin



/* Here, Created Multiple field for this module form */

A)  This is a Form.php files Where you can create your Custom Field's as per Requirement
  Path for your File is  "app\code\local\[Namespace]\[Module Name]\Block\Adminhtml\[Modele Name]\Edit\Tab\Form.php"


  protected function _prepareForm()
  {
      $form = new Varien_Data_Form();
      $this->setForm($form);
      $fieldset = $form->addFieldset('beautygirl_form', array('legend'=>Mage::helper('beautygirl')->__('Item information')));
   
      $fieldset->addField('title', 'text', array(
          'label'     => Mage::helper('beautygirl')->__('Title'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
      ));

 $fieldset->addField('status', 'select', array(
          'label'     => Mage::helper('beautygirl')->__('Status'),
          'name'      => 'status',
          'values'    => array(
              array(
                  'value'     => 1,
                  'label'     => Mage::helper('beautygirl')->__('Enabled'),
              ),

              array(
                  'value'     => 2,
                  'label'     => Mage::helper('beautygirl')->__('Disabled'),
              ),
          ),
      ));

  $fieldset->addField('startdate', 'date', array(
            'name'      => 'startdate',
            'title'     => Mage::helper('beautygirl')->__('Start Date'),
            'label'     => Mage::helper('beautygirl')->__('Start Date'),
'image'  => Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'/adminhtml/default/default/images/grid-cal.gif',
//'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
          //'format' => 'dd-MM-yyyy',
  'format' => 'yyyy-MM-dd',
//'format' => Varien_Date::DATE_INTERNAL_FORMAT,
            'required'  => true,
        ));

$fieldset->addField('enddate', 'date', array(
            'name'      => 'enddate',
            'title'     => Mage::helper('beautygirl')->__('End Date'),
            'label'     => Mage::helper('beautygirl')->__('End Date'),
'image'  => Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'/adminhtml/default/default/images/grid-cal.gif',
//'format' => 'MM-dd-yyyy',
'format' => 'yyyy-MM-dd',
            'required'  => true,
        ));


      $fieldset->addField('filename', 'file', array(
          'label'     => Mage::helper('beautygirl')->__('File'),
          'required'  => true,
          'name'      => 'filename',
 ));

 $fieldset->addField('girlone', 'text', array(
          'label'     => Mage::helper('beautygirl')->__('Girl One'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'girlone',
      ));
       
      $fieldset->addField('girlonecontent', 'editor', array(
          'name'      => 'girlonecontent',
          'label'     => Mage::helper('beautygirl')->__('Content'),
          'title'     => Mage::helper('beautygirl')->__('Content'),
          'style'     => 'width:700px; height:500px;',
          'wysiwyg'   => false,
          'required'  => true,
      ));

   
      if ( Mage::getSingleton('adminhtml/session')->getBeautygirlData() )
      {
          $form->setValues(Mage::getSingleton('adminhtml/session')->getBeautygirlData());
          Mage::getSingleton('adminhtml/session')->setBeautygirlData(null);
      } elseif ( Mage::registry('beautygirl_data') ) {
          $form->setValues(Mage::registry('beautygirl_data')->getData());
      }
      return parent::_prepareForm();
  }
}


B) This is the Second Step ::: app\code\local\[Namespace] \[Module Name]\controller/Adminhtml/yourcontrollerfile.php

/* For save your Module Item open controller file of module */
/* path = controller/Adminhtml/yourcontrollerfile.php*/
/* Here change two functions ""editAction"" and ""SaveAction"" */


In EditAction
/* Here I Use Example for create 2 extra tabs Mean I have Tabs Like this */
/* 1. Form[Default]  2. Form1  3.  Form2 */

public function editAction() {
$id     = $this->getRequest()->getParam('id');
$model  = Mage::getModel('beautygirl/beautygirl')->load($id);

if ($model->getId() || $id == 0) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}

$data1 = Mage::getSingleton('adminhtml/session')->getForm1Data(true);
if (!empty($data1)) {
$model->setData($data1);
}

$data2 = Mage::getSingleton('adminhtml/session')->getForm2Data(true);
if (!empty($data2)) {
$model->setData($data2);
}
        }


In SaveAction

/* Here I Use Example for create 2 extra tabs Mean I have Tabs Like this */
/* 1. Form[Default]  2. Form1  3.  Form2 */
/* In Save Action, We Save Data of Forms Which are created By us */


public function saveAction() {
if ($data = $this->getRequest()->getPost()) {

if(isset($_FILES['filename']['name']) && ($_FILES['filename']['name'] != '')  &&
     (isset($_FILES['filename1']['name']) && ($_FILES['filename1']['name'] != '')) &&
     (isset($_FILES['filename2']['name']) && ($_FILES['filename2']['name'] != ''))) {


try {
/* Starting upload */ 
/* This is Upload Image of Forms FileUpload Field */

$uploader = new Varien_File_Uploader('filename');
$uploader1 = new Varien_File_Uploader('filename1');
$uploader2 = new Varien_File_Uploader('filename2');


              // Any extention would work
          $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
          $uploader->setAllowRenameFiles(false);
          // Any extention would work
          $uploader1->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader1->setAllowRenameFiles(false);
// Any extention would work
          $uploader2->setAllowedExtensions(array('jpg','jpeg','gif','png'));
          $uploader2->setAllowRenameFiles(false);



             // Set the file upload mode
          // false -> get the file directly in the specified folder
          // true -> get the file in the product like folders
          // (file.jpg will go in something like /media/f/i/file.jpg)
          $uploader->setFilesDispersion(false);
          $uploader1->setFilesDispersion(false);
          $uploader2->setFilesDispersion(false);



              // We set media as the upload dir
$path = Mage::getBaseDir('skin') . DS.('frontend').DS.('default').DS.('beautydem').DS.('images').DS.('Beautygirl').DS ;
$uploader->save($path, $_FILES['filename']['name'] );
          // We set media as the upload dir
          $path1 = Mage::getBaseDir('skin') . DS.('frontend').DS.('default').DS.('beautydem').DS.('images').DS.('Beautygirl').DS ;
$uploader1->save($path1, $_FILES['filename1']['name']);
          $path2 = Mage::getBaseDir('skin') . DS.('frontend').DS.('default').DS.('beautydem').DS.('images').DS.('Beautygirl').DS ;
          $uploader2->save($path2, $_FILES['filename2']['name']);





}
    catch (Exception $e)
   {
   
  }
     
          //this way the name is saved in DB
  $data['filename'] = $_FILES['filename']['name'];
$data['filename1'] = $_FILES['filename1']['name'];
$data['filename2'] = $_FILES['filename2']['name'];
   }

            /* If you use multiselection then for insert value as comm seperated in database use below lines */

           $data['girloneproductid']=implode(',',$data['girloneproductid']);
         $data['girltwoproductid']=implode(',',$data['girltwoproductid']);
$data['girlthreeproductid']=implode(',',$data['girlthreeproductid'])



$model = Mage::getModel('beautygirl/beautygirl');
         $model->setData($data)
        ->setId($this->getRequest()->getParam('id'));

try
  {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL)
          {
              $model->setCreatedTime(now())
            ->setUpdateTime(now());
        }
          else
          {
$model->setUpdateTime(now());
}

$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('beautygirl')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
       Mage::getSingleton('adminhtml/session')->setForm1Data(false);
Mage::getSingleton('adminhtml/session')->setForm2Data(false);


         $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
         return;
        }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('beautygirl')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
}

Saturday 1 September 2012

Magento : Get Category name,Product ID and SKU in Multi-selection field in admin for custom module which created using module creator

For this you can change on this file path

local/yourmodule/block/adminhtml/yourmodulename/edit/tab/form.phtml

you use below functions,

<?php

class Addon_Testing_Block_Adminhtml_Testing_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
    // This for get category detail

    public function buildCategoriesMultiselectValues(Varien_Data_Tree_Node $node, $values, $level = 0)
    {
        $level++;
        //-----new start for only 3 level category
        if($level>3)
        {
        return $values;    
        }
        //-----new close
        $values[$node->getId()]['value'] =  $node->getId();
        $values[$node->getId()]['label'] = str_repeat("---", $level) . $node->getName();
       
        foreach ($node->getChildren() as $child)
        {
            $values = $this->buildCategoriesMultiselectValues($child, $values, $level);
           print_r($values); 
        }
       
        return $values;
    }
   
    public function load_tree()
    {
        $tree = Mage::getResourceSingleton('catalog/category_tree')->load();
   
        $store = 1;
        $parentId = 1;
   
        $tree = Mage::getResourceSingleton('catalog/category_tree')->load();
   
        $root = $tree->getNodeById($parentId);
       
        if($root && $root->getId() == 1)
        {
            $root->setName(Mage::helper('catalog')->__('Root'));
        }
       
        $collection = Mage::getModel('catalog/category')->getCollection()
            ->setStoreId($store)
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('is_active');
       
        $tree->addCollectionData($collection, true);

        return $this->buildCategoriesMultiselectValues($root, array());   
    }
   
  //This is for product id
    function getProductCollection()
    {
       $model = Mage::getModel('catalog/product'); //getting product model
        $collection = $model->getCollection(); //products collection
       
       
                 $count = 0;
       
                foreach ($collection as $product) //loop for getting products
                {
                    $a = $count++;
                    $values[$a]['value'] = $a;
                    $values[$a]['label'] = $product->getId();
                 }                                          
                return $values;               
    }
   
     // This is for Product Sku
    function getProductCollectionskus()
    {
       $model = Mage::getModel('catalog/product'); //getting product model
        $collection = $model->getCollection(); //products collection
           
                $count = 0;
       
                foreach ($collection as $product) //loop for getting products
                {
                    $a = $count++;
                    $values[$a]['value'] = $a;
                    $values[$a]['label'] = $product->getSku();
                }                                             
                return $values;               
    }
  protected function _prepareForm()
  {
      $form = new Varien_Data_Form();
      $this->setForm($form);
      $fieldset = $form->addFieldset('testing_form', array('legend'=>Mage::helper('testing')->__('Item information')));
    
      $fieldset->addField('title', 'text', array(
          'label'     => Mage::helper('testing')->__('Title'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
      ));
     
       $fieldset->addField('girl', 'text', array(
          'label'     => Mage::helper('testing')->__('Girl'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'girl',
      ));


      $fieldset->addField('filename', 'file', array(
          'label'     => Mage::helper('testing')->__('File'),
          'required'  => false,
          'name'      => 'filename',
      ));
   
     // Here, call above Functions
      $pids = $this->getProductCollection();
      $skus = $this->getProductCollectionskus();
      $categories_values = $this->load_tree();
      //echo "<pre>";
      //print_r($pids);
      //echo "</pre>";     
      //$categories_values = $this->load_tree();
        //echo '<pre>';            
        //print_r($skus);
        //echo "</pre>";
     
    $fieldset->addField('productid', 'multiselect', array(
                'name' => 'productid',
                'label' => Mage::helper('testing')->__('Select Product ID'),                  
                'required' => true ,               
                'values' => $pids,
               
                ));       
               
    $fieldset->addField('productsku', 'multiselect', array(
                'name' => 'productsku',
                'label' => Mage::helper('testing')->__('Select Product Sku'),                  
                'required' => true ,               
                'values' => $skus,               
                ));   
               
    $fieldset->addField('productsku', 'multiselect', array(
                'name' => 'productsku',
                'label' => Mage::helper('testing')->__('Select Category'),                  
                'required' => true ,               
                'values' => $categories_values,               
                ));              
               
     
     
       $fieldset->addField('content', 'editor', array(
          'name'      => 'content',
          'label'     => Mage::helper('testing')->__('Content'),
          'title'     => Mage::helper('testing')->__('Content'),
          'style'     => 'width:700px; height:500px;',
          'wysiwyg'   => false,
          'required'  => true,       
      ));
       
      $fieldset->addField('status', 'select', array(
          'label'     => Mage::helper('testing')->__('Status'),
          'name'      => 'status',
          'values'    => array(
              array(
                  'value'     => 1,
                  'label'     => Mage::helper('testing')->__('Enabled'),
              ),

              array(
                  'value'     => 2,
                  'label'     => Mage::helper('testing')->__('Disabled'),
              ),
          ),
      ));         
    
      if ( Mage::getSingleton('adminhtml/session')->getTestingData() )
      {
          $form->setValues(Mage::getSingleton('adminhtml/session')->getTestingData());
          Mage::getSingleton('adminhtml/session')->setTestingData(null);
      } elseif ( Mage::registry('testing_data') ) {
          $form->setValues(Mage::registry('testing_data')->getData());
      }
      return parent::_prepareForm();
  }
}

Thursday 23 August 2012

Magento : Get order detail on checkout success page


You can get Order Detail using this,

File Location = frontend/base/default/template/checkout/success.phtml

<?php

echo $order = Mage::getModel('sales/order')->load(Mage::getSingleton('checkout/session')->getLastOrderId());
$items = $order->getAllItems();
foreach ($items as $item){
$product = $item->getProduct();
$proids = $item->getProductId();
$name = $item->getName();
$storeId = 1;
echo "<br/>";
}
?>

Reference

http://developerafroz.blogspot.in/2012_01_01_archive.html

http://store.redstage.com/blog/2012/05/31/magento-1-5-fedex-shipping

http://smashingspy.com/32-best-jquery-popup-window-dialog-box-example/

http://xhtmlandcsshelp.blogspot.in/2010_10_01_archive.html

http://spenserbaldwin.com/magento/show-product-review-on-product-page

http://www.desv.us/how-to-use-select-update-delete-and-insert-queries-in-magento.html

http://www.desv.us/category/magento-tutorials/page/3

http://www.imagedia.com/2010/02/how-to-change-order-status-in-magento/

skype = boy-named-sue

//For the Admin Part

http://www.excellencemagentoblog.com/magento-admin-form-field

http://magentools.com/blog/magento-certification-preparation-study-guide-answers/ // Magento Exam


http://tim-bezhashvyly.github.io/media/four-ways-to-customize-a-cart-item.pdf  

Tuesday 21 August 2012

Magento : Enable / Disable magento admin debug mode

Just run this query:


==> INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', 0, 'dev/debug/template_hints', 1),
('default', 0, 'dev/debug/template_hints_blocks', 1);


To disable them again, run this query

==> UPDATE core_config_data set value = 0 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'\


To enable again run this query

==> UPDATE core_config_data set value = 1 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'