PHP SOLUTIONS

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

Saturday 6 April 2013

Magento : Programmatically create product from front-end

Hi,

Here, For the Create the Product directly from Front Side without open Admin.

There are few steps to follow,

1)  First of all you need to create One user in Admin,

   For, Create the User, use this Path in admin,

   In Admin,   System-> Web-Service->SOAP/XML-RPC-Users

   /* Here you create the user for our API to insert the Product */

  And Assign role to that user  =   System-> Web-Service->SOAP/XML-RPC-Roles

  /* Here Assign Role for ADD/UPDATE/DELETE product */


2)  Create Necessary field's in Form of Page,

     As an Example =>I create product, And Action of Account Controller.

           <form method="POST" action="<?php Mage::getBaseUrl() ?>customer/account/create">

                /* Required Fields for Product like Title,Price,Description */

              /* Note :::  If you want to upload the Multiple Image then use this Image Field */

             <div class="title">
                    <div id='TextBoxesGroup'>
                          <div id="TextBoxDiv1">
                                <label>Image 1</label>
                                <input type="file"  name="docname1" />
                          </div>
                    </div>
             </div>
            <div class="btn" style="margin:15px 317px 0 0; float:right;">
                      <input type='button' value='Add ImageBox' id='addButton'>
                      <input type='button' value='Remove ImageBox' id='removeButton'>
            </div>




          </form>

         /* Note ::::  Write this script also bottom of the Page */

        <script type="text/javascript">
               jQuery(document).ready(function(){
                                  var counter = 2;
                                  jQuery("#addButton").click(function () {
                                             if(counter>5){
                                             alert("Maximum 5 Image Upload");
                                             return false;
                                 }  
                                 var newTextBoxDiv = jQuery(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
                                 newTextBoxDiv.after().html('<label>Image '+ counter + ' : </label>' + '<input type="file" name="docname' + counter  + '" value="" >');
                                 newTextBoxDiv.appendTo("#TextBoxesGroup");
                                 counter++;
                                });


                              jQuery("#removeButton").click(function () {
                                          if(counter==2){
                                                  alert("At Least One ImageBox Required");
                                                  return false;
                                         }  
                                         counter--;
                                         jQuery("#TextBoxDiv" + counter).remove();
                              });
                               jQuery("#getButtonValue").click(function () {
                               var msg = '';
                                for(i=1; i<counter; i++){
                                           msg += "\n Textbox #" + i + " : " + jQuery('#textbox' + i).val();
                                 }
                                 alert(msg);
                     });
                     });
              </script>




3) Then Simpally Copy/Paste Below Code in your Account Controller.

   Path->  Customer/controller/AccountController.php

     /* Copy This  */

        $proxy = new SoapClient(Mage::getBaseUrl().'api/soap/?wsdl');
        $sessionId = $proxy->login('kaushik', 'developer1');

        $attributeSets = $proxy->call($sessionId, 'product_attribute_set.list');
        $set = current($attributeSets);


         ///  Required Data.............
        $_ptitle=$_POST['a_title'];
        $_psku=$_POST['a_title'].time();
        $_pdes=$_POST['a_description'];
        $_pprice=$_POST['a_price'];
      
      

        $newProductData = array(
            'name'              => $_ptitle,            
            'websites'          => array(1), // array(1,2,3,...)
            'short_description' => $_pdes,
            'description'       => $_pdes,
            'status'            => 1,
            'weight'            => 0,
            'tax_class_id'      => 0,
            'categories'        => array(3),    //3 is the category id 
            'price'             => $_pprice
          
        );


     // Create new product
        $proxy->call($sessionId, 'product.create', array('simple', $set['set_id'], $_psku, $newProductData));
        $proxy->call($sessionId, 'product_stock.update', array($_psku, array('manage_stock'=>0)));
         
        /*Upload Image */

       for($i=1;$i<=10;$i++)
        {

        if($_FILES["docname".$i.""]["name"]!='')   
        {
                  $_FILES["docname".$i.""]["name"]; 
               
               
         /////// image upload and move to product_upload folder in media START.........
       
               $absolute_path = Mage::getBaseDir('media') . DS .('product_upload');
               $relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
              // File Upload
   
              $files = time().$_FILES["docname".$i.""]["name"];
              if(isset($files) && $files != '')
              {  
              try
              {
                      if(file_exists($absolute_path.DS.$files))
                      {
                             $var = rand(0,99);
                             $files = $var.'_'.$files;
                      }
                      // Starting upload
                     $uploader = new Varien_File_Uploader('docname'.$i);
                      // Any extention would work
                     $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                     $uploader->setAllowRenameFiles(false);
           
                      //false -> get the file directly in the specified folder
                     //true -> get the file in the product like folders /media/catalog/product/file.gif

                     $uploader->setFilesDispersion(false);

                     //We set media as the upload dir
                     $uploader->save($absolute_path, $files);
             }
             catch(Exception $e)
            {
                   Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
            // Your uploaded file Url will be
            $file_url = $files;
                                                                        $mypath=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'product_upload/'.$file_url;
          Mage::getSingleton('core/session')->setFrontfilelogo($file_url);
      }

      }
       //// Image Upload END............
      ///  product image save start.......   
       
        $newImage = array(
                    'file' => array(
                            'name' => 'file_name',
                            'content' => base64_encode(file_get_contents($mypath)),
                            'mime'    => 'image/jpeg'
                            ),
                'label'    => 'docname',
                'position' => 2,
                'types'    => array('image', 'small_image', 'thumbnail'),
                'exclude'  => 0
            );

        $imageFilename = $proxy->call($sessionId, 'product_media.create', array($_psku, $newImage));
       
        ///  product image save END.......   
   
            }
            else
            {
                break;
            }
        }
           
        $this->_redirect('*/*/your page to redirect');
    }







,