PHP SOLUTIONS

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

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();
  }
}