PHP SOLUTIONS

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

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, 7 April 2016

Command Promt : php is not recognized as an internal or external command

Set PHP environment variable to the System for run PHP from CMD (Command Prompt)
Step 1 : Open properties of My Computer (Right Click on My Computer)

Step 2 : Click on "Advance system settings"

 Step 3 : Can see popup of  "System Properties"

              Click on "Environment Variable" button


 Step 4 : Can see popup of Environment Variable

              Set System variable path for PHP 


              Append C:\wamp\bin\php\php5.5.12; at last  (Note :- replace php5.5.12 with your php version)

     

Step 5 : Close / Open CMD (Command Prompt) again
Now, It's solved !

Saturday, 6 June 2015

PHP : Get Array of CSV file in PHP

Hello Friends,

Method 2::

Here, second method for read the CSV file, its returns Array of the CSV data !

PHP
<?php

          $file = "Path of File Name";
          $csv = new Varien_File_Csv();
          $data = $csv->getData($file);

         Print_r($data); /*This will give Array of CSV file data*/

?>

If you want to read CSV line by line you can use Method 1 also,

Also, need to get PHP array to jQuery refer this Link,

May this help you !

PHP : Read PHP array using jQuery JSON

Hello Friends,


    I got this method after so many surfing, I hope this will help you for read PHP array to the jQuery.

    Using this can get the PHP array in JavaScript array!
PHP
   <?php

          $file = "Path of File Name";
          $csv = new Varien_File_Csv();
          $data = $csv->getData($file);

         Print_r($data); /*This will give Array of CSV file data*/

    ?>

   <script type="text/javascript">

          var sample = new Array();

          var vals = 'sample ';

          sample [vals] = '<?php echo json_encode($data) ?>';

         var sample_data = JSON.parse(sample ["sample"]);

   </script>

     Hope, this will useful to you !

Monday, 31 March 2014

Magento Images not displayed in Admin

HI,

    Some times in Magento create amazing issues, in admin or for fornt end also

    Recently, I am getting this type of issue, In side admin I can't see the product images after the Inserting the product

Product Images no display in admin


for solve this type of issue

Just open media directory using FTP and just change the name of .htaccess to .htaccess_old

And you have solve the Image issue.

Enjoy::::

Friday, 28 March 2014

PHP : Read CSV file line by line

There are 2 type for read CSV file using PHP script.

Method 1 ::

Using this can read CSV line by line, can get any number of cell value

$line = 1;
$csv = array(); //new array.
if (($handle = fopen("test.csv", "r")) !== FALSE) { // Read csv file
    while (($obj = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($obj);
        echo "<label> $num fields in line $row: <br /></label>\n";
        $line++;
        for ($i=0; $i < $num; $i++) {
            echo $obj[$i] . "<br />\n";
        }
        $csv[] = $obj;
    }
    fclose($handle);
}
echo $csv[2][1]; //prints the 3th row, second column.



If want to get Array of the CSV then use Method 2 here,

Saturday, 6 July 2013

Magento : Using Observer add the cart quote details to order item

Hi,

For Set the Cart Quote Items to the Order using the Observer. Using the "sales_convert_quote_item_to_order_item" Observer we can Add Custom Details of cart to the Order in magento.


1) Refer this Post = http://developerforums.blogspot.com/2013/07/using-observer-add-custom-price-for.html

Notice ::::>
                      Using this Post you can only set the Custom Details and Price to cart only, so for Save that Details to the Order you need to use another Event of Magento.  


2) Then Open your Module config.xml

    Copy-Paste below code Inside  <event> ...................   </event>  Tag.

    <sales_convert_quote_item_to_order_item> <!--Here Event Name as per your Requirement -->
                <observers>   
                    <{Namespace}_{Module Name}_Model_Observer>              
                        <type>singleton</type>
                        <class>{Namespace}_{Module Name}__Model_Observer</class>
                        <method>setdetailstocart</method>
                    </{Namespace}_{Module Name}__Model_Observer>                  
                </observers>      
   </sales_convert_quote_item_to_order_item>

3)  Open your   "Model/Observer.php"

   Use below Code

  class {Namespace}/{Module Name}_Model_Observer
  {
         $quoteItem = $observer->getItem();
            if ($additionalOptions = $quoteItem->getOptionByCode('additional_options'))
            {
                $orderItem = $observer->getOrderItem();
                $options = $orderItem->getProductOptions();
                $options['additional_options'] = unserialize($additionalOptions->getValue());
                $orderItem->setProductOptions($options);
            }
}

4) Clear all Cache and Index of your Site


Enjoy, This is work for me in Magento 1.7.0.2

    

Tuesday, 2 July 2013

Magento : Using Observer add custom price and details for cart product

Hi,

For Set the Custom Price in Cart using the Observer. Using the Observer we can perform many events in magento, There are so many different Events to make changes in Magento.



A) First Create Module using the Module Creator in admin

B) then Open Module Config.xml file which is located at etc directory of Module

C) Use Below code using as per your event requirement

<frontend>
...................
<events>
            <checkout_cart_product_add_after>  <!--Here Event Name as per your Requirement -->
                <observers>   
                    <{Namespace}_{Module Name}_Model_Observer>              
                        <type>singleton</type>
                        <class>{Namespace}_{Module Name}__Model_Observer</class>
                        <method>setcustomprice</method>
                    </{Namespace}_{Module Name}__Model_Observer>                  
                </observers>
            </checkout_cart_product_add_after>
        </events>
 .................      
 </frontend>

D) Now, Create Observer.php in Model Directory

    {Namespace}/{Module Name}/Model/Observer.php

E) Use Below Code

 
class {Namespace}/{Module Name}_Model_Observer
{
   
       public function setcustomprice(Varien_Event_Observer $observer) {
                      
        $item = $observer->getQuoteItem();
        // Check if Product have parent item.
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
      
        // This is for add the Custom Information about Product Item
        $additionalDetail = array(array(
         'code' => 'custom_details',
         'label' => 'This text is displayed through additional options',
         'value' => 'ID is ' . $item->getProductId() . ' and SKU is ' . $item->getSku()
         ));
         $item->addOption(array(
         'code' => 'additional_options',
         'value' => serialize($additionalOptions),
         ));
        

        // Load the custom price
        $price = 123; //Here, set the Custom Price for Item
        // Set the custom price
        $item->setCustomPrice($price); // This set the Custom Price in Quote of cart
        $item->setOriginalCustomPrice($price);
        // Enable super mode on the product.
        $item->getProduct()->setIsSuperMode(true); 

        }
      
}

F) Clear all Cache and Index of your Site


Enjoy, This is work for me in Magento 1.7.0.2



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







Thursday, 3 January 2013

Magento : Add Fixed price to same Product for a Multiple Qty in cart

Hi,

 Actually This code for set custom price to each product in cart when it add to cart from Category Page,

That's why I found some solution for that add custom value to the Row Total of product

For that

A)  Open code\core\Mage\Sales\Model\Quote\Item\Abstract.php

     Find,  Function calcRowTotal()

  You can see this lines,  

    $total      = $this->getStore()->roundPrice($this->getCalculationPriceOriginal() * $qty;
    $baseTotal  = $this->getBaseCalculationPriceOriginal() * $qty;


    Simply, Add your custom value here

   $temp = 10;  /* Now $10 inserted in to the Row total of Product in cart */

    $total      = ($this->getStore()->roundPrice($this->getCalculationPriceOriginal()) * $qty) + $temp ;
    $baseTotal  = ($this->getBaseCalculationPriceOriginal() * $qty) + $temp;


Here the Basic idea for, Where to change for add custom value of row total of product
you can also set this dynamic as per your requirement,

Enjoy ::


   


Magento : Remove Shipping Method form Checkout

Hi,

  If in any case need to remove the Shipping Method from the site, then Now easily remove that by macking change in  following steps,

  For Remove Shipping Methods you need to change its function 

  This code is working for me in 1.7.0.2 but you can try this for older version also

A)  Open Mage/checkout/controllers/Onepagecontroller.php

     In this File Go to on  "function saveBillingAction() "

    Check this line in this function and change

     From

       elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
                    $result['goto_section'] = 'shipping_method';
                    $result['update_section'] = array(
                        'name' => 'shipping-method',
                        'html' => $this->_getShippingMethodsHtml()
                    );

     To

       elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
                    $result['goto_section'] = 'payment';
                    $result['update_section'] = array(
                        'name' => 'payment-method',
                        'html' => $this->_getPaymentMethodsHtml()
                    );

 B)  Now, In Onepagecontroller.php

   Go to on this function  "public function saveShippingAction()"

  change this function

  From

   public function saveShippingAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost('shipping', array());
            $customerAddressId = $this->getRequest()->getPost('shipping_address_id', false);
            $result = $this->getOnepage()->saveShipping($data, $customerAddressId);

            if (!isset($result['error'])) {
                $result['goto_section'] = 'shipping_method';
                $result['update_section'] = array(
                    'name' => 'shipping-method',
                    'html' => $this->_getShippingMethodsHtml()
                );
            }
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
        }
    }      


To

public function saveShippingAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost('shipping', array());
            $customerAddressId = $this->getRequest()->getPost('shipping_address_id', false);
            $result = $this->getOnepage()->saveShipping($data, $customerAddressId);

            if (!isset($result['error'])) {
                $result['goto_section'] = 'payment';
                $result['update_section'] = array(
                    'name' => 'payment-method',
                    'html' => $this->_getPaymentMethodsHtml()
                );
            }
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
        }
    }


C) After that Open Code/core/mage/sales/model/service/Quote.php

  Find this function " protected function _validate() "

  Here comment below code

  if ($addressValidation !== true) {
                Mage::throwException(
                    Mage::helper('sales')->__('Please check shipping address information. %s', implode(' ', $addressValidation))
                );
            }
            $method= $address->getShippingMethod();
            $rate  = $address->getShippingRateByCode($method);
            if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
                Mage::throwException(Mage::helper('sales')->__('Please specify a shipping method.'));
            }

D) Open file code/core/mage/checkout/block/onepage/shipping/Method.php

   This is hide the Shipping Method tab from the Onepage checkout during Place the order

   Find below function

    public function isShow()
    {
        return !$this->getQuote()->isVirtual();
    }

   Change it with

    public function isShow()
    {
                return false;
    }


   Now, Finally you can check that your Shipping Method will remove from your site.

  Enjoy ::