Tuesday, May 27, 2014

Magic function and it's use in magento

As we know in pho 5 they have implemented some magic function which is as follow. 
 __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone().

In between that magento is using   __get, __set & __call


Thursday, May 22, 2014

Magento Custom single table extension

Suppose we have a table call "customer_product_like" having field (entity_id, store_id, customer_id, )

Now i want to insert data in this table then the code will be
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$fields = array();
$fields['status']= $postData['like'];
$fields['store_id']= Mage::app()->getStore()->getId();
$fields['product_id']= $postData['prodId'];
$fields['customer_id']= $customerId;
$connection->insert('customer_product_like', $fields);

for update
$where = "entity_id = '".$customerProductLikeId."'";
$connection->update('customer_product_like', $fields, $where);

For select
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
 $select = $connection->select()
                    ->from('customer_product_like', array('*'))
                    ->where("product_id = '".$prodId."' AND customer_id = '".$customerId."' AND store_id = '".$storeId."'");
$result = $connection->fetchRow($select);   OR   $result = $connection->fetchAll($select);

Wednesday, May 21, 2014

How to get all available shipping carrier rate by zip code and country code in Magento

If you have country code and zip code then you can find out the all available shipping carrier rate by following code in magento.


$zipcode = '711101';
$country = 'IN';                    
          
$cart = Mage::getSingleton('checkout/cart');
$address = $cart->getQuote()->getShippingAddress();

$address->setCountryId($country)->setPostcode($zipcode)->setCollectShippingrates(true);
$rates = $address->collectShippingRates()->getGroupedAllShippingRates();

foreach ($rates as $carrier) {
             foreach ($carrier as $rate) {
                            print_r($rate->getData());
               }
 }


Saturday, April 19, 2014

How to get innerhtml by id in php

This following code will bring html element inner html by it's id.


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);
$newDom = new domDocument;
libxml_use_internal_errors(true);
$newDom->loadHTML($html);
libxml_use_internal_errors(false);
$newDom->preserveWhiteSpace = false;
$newDom->validateOnParse = true;
     
$sections = $newDom->saveHTML($newDom->getElementById('element id'));  
echo $sections;

Sunday, March 2, 2014

Magento Install Script Will Not Runing

Work your way through <a href="http://alanstorm.com/magento_setup_resources">this article</a> to make sure you don't have any misunderstanding of what the setup resources do, how they work, and how you can troubleshoot them.

Once you've done that, from everything you've said on this question thread it sounds like you're getting your resource "installed", but that your install script never runs. My guess is that the version number you used in

    //0.0.1 is your version number
    mysql4-install-0.0.1.php
   
didn't match up with the version of your module

    <modules>
        <Nie_Nie>
            <version>?.?.?</version>
        </Nie_Nie>
    </modules>
   
Those should match for the script to run.  I **think** Magento is smart enough to run previous versions if it finds them, but the code in the setup resources is the kind that's hard to follow, so I always make sure they match.

Regardless, here's how you can see which file(s) magento is trying to run when it runs your setup resource.  Delete any entries from <code>core_resource</code> related to your module.  Clear your cache.  Then find the following locations in the setup class

    File: app/code/core/Mage/Core/Model/Resource/Setup.php
   
    protected function _modifyResourceDb($actionType, $fromVersion, $toVersion)
    {
        ...   
       
        $sqlFilesDir = Mage::getModuleDir('sql', $modName).DS.$this->_resourceName;       

        if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
            return false;
        }
       
        ...
       
        $sqlDir->close();

        if (empty($arrAvailableFiles)) {
            return false;
        }
       
        ...
       
        $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
        if (empty($arrModifyFiles)) {
            return false;
        }
       
and then modify them to add some temporary debugging exceptions       

        if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
            throw new Exception("$sqlFilesDir not found");
            return false;
        }
       
        ...
       
        if (empty($arrAvailableFiles)) {
            throw new Exception("No files found to run");
            return false;
        }
       
        ...

        $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
        if (empty($arrModifyFiles)) {
            throw new Exception("No valid upgrade files found to run for ");
            return false;
        }
       
        throw new Exception("If you're getting here, we have a file.  Remove your exceptions here and place one in your installer to make sure it's the one you think it is.");
       
Reload the page and you'll get exception text complaining about whatever Magento can't find.  That should be enough to help you track down which installer script Magento is trying to run, but failing to find. Just remember to delete your module's row in <code>core_resource</code> and to clear your cache. (Magneto caches which modules need to check for an install/upgrade)

If that doesn't work, start digging into the logic of <code>applyAllDataUpdates</code> and figure out why the class isn't including  your installer file.

Monday, February 24, 2014

Reorder via Code in magennto

I have create a extension for reorder please find the following code for it


<?php class Cdotsys_ScheduleOrder_ScheduleorderController extends Mage_Core_Controller_Front_Action{
private $_storeId = '1';
private $_groupId = '1';
private $shipping_methord = 'flatrate_flatrate';
private $_sendConfirmation = '0';
private $orderData = array();
private $_sourceCustomer;

public function IndexAction() {

              $this->loadLayout();   
              $this->getLayout()->getBlock("head")->setTitle($this->__("Scheduleorder"));
                    $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
              $breadcrumbs->addCrumb("home", array(
                        "label" => $this->__("Home Page"),
                        "title" => $this->__("Home Page"),
                        "link"  => Mage::getBaseUrl()
                   ));

              $breadcrumbs->addCrumb("scheduleorder", array(
                        "label" => $this->__("Scheduleorder"),
                        "title" => $this->__("Scheduleorder")
                   ));

        $scheduleorders = Mage::getModel('scheduleorder/scheduleorder')->getCollection();    
        foreach($scheduleorders as $scheduleorder){             
            $personsOrder = Mage::getModel('sales/order')->load($scheduleorder->getOrderId());              
            //$personsOrder->setReordered(true);
            $items = $personsOrder->getAllItems();  
            foreach($items as $item){                   
                $products[$item->getProductId()] = array('qty' => $item->getQtyOrdered());                  
            } 
            $this->shipping_methord = $personsOrder->getShippingMethod()
            $customer = Mage::getModel('customer/customer')->load($personsOrder->getCustomerId());
            $this->setOrderInfo($customer,$products);
            $this->create();
            $personsOrder->setPaymentMethod('cashondelivery');

            $order_model = Mage::getSingleton('adminhtml/sales_order_create');
            /*$order_model->setPaymentData('cashondelivery');
            $order_model->getQuote()->getPayment()->addData('cashondelivery');
            $order_model->setShipping('flatrate_flatrate');
            $order_model->getQuote()->getShipping()->addData('flatrate_flatrate');
            $order_model->getQuote()->setShipping(array('method' => 'flatrate_flatrate'));
            $order_model->getQuote()->setPayment(array('method' => 'cashondelivery'));

            $order_model->initFromOrder($personsOrder);             
            $order_model->createOrder();*/
        }

              $this->renderLayout(); 

    }

public function setOrderInfo(Mage_Customer_Model_Customer $sourceCustomer,$products){
        $this->_sourceCustomer = $sourceCustomer;
        //You can extract/refactor this if you have more than one product, etc.
        $Billingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultBilling());
        $Shippingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultShipping());
        $this->orderData = array(
        'session'       => array(
                            'customer_id'   => $this->_sourceCustomer->getId(),
                            'store_id'      => $this->_storeId,
                            ),
        'payment'       => array(
                            'method'    => 'checkmo',
                            ),  
        'add_products'  =>$products,
        'order' => array(
                        'currency' => 'USD',
                        'account' => array(
                                'group_id' => $this->_groupId,
                                'email' => $this->_sourceCustomer->getEmail()
                                ),
                        'billing_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultBilling(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Billingaddress->getStreet(),''),
                                                'city' => $Billingaddress->getCity(),
                                                'country_id' => $Billingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Billingaddress->getRegionId(),
                                                'postcode' => $Billingaddress->getPostcode(),
                                                'telephone' => $Billingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                        'shipping_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultShipping(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Shippingaddress->getStreet(),''),
                                                'city' => $Shippingaddress->getCity(),
                                                'country_id' => $Shippingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Shippingaddress->getRegionId(),
                                                'postcode' => $Shippingaddress->getPostcode(),
                                                'telephone' => $Shippingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                                                'shipping_method' => $shipping_methord,
                                                'comment' => array(
                                                'customer_note' => 'This order has been created by scheduler order script.',
                                                ),
                            'send_confirmation' => $this->_sendConfirmation
        ),
        );
}   

protected function _getOrderCreateModel()
{
    return Mage::getSingleton('adminhtml/sales_order_create');
}
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession()
{
    return Mage::getSingleton('adminhtml/session_quote');
}
/**
* Initialize order creation session data
*
* @param array $data
* @return Mage_Adminhtml_Sales_Order_CreateController
*/
protected function _initSession($data)
{
/* Get/identify customer */
    if (!empty($data['customer_id'])) {
        $this->_getSession()->setCustomerId((int) $data['customer_id']);
    }
/* Get/identify store */
    if (!empty($data['store_id'])) {
        $this->_getSession()->setStoreId((int) $data['store_id']);
    }
  return $this;
}

public function create(){
    $orderData = $this->orderData;

    if (!empty($orderData)) {
            $this->_initSession($orderData['session']);
        try {
                $this->_processQuote($orderData);
                if (!empty($orderData['payment'])) {
                    $this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
                    $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
                }

                Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
                $_order = $this->_getOrderCreateModel()->importPostData($orderData['order'])->createOrder();
                $this->_getSession()->clear();
                Mage::unregister('rule_data');
                return $_order;
        }
        catch (Exception $e){
            Mage::log("Order save error...");
        }
    }
    return null;
}

protected function _processQuote($data = array()){
    /* Saving order data */
    if (!empty($data['order'])) {
        $this->_getOrderCreateModel()->importPostData($data['order']);
    }
    $this->_getOrderCreateModel()->getBillingAddress();
    $this->_getOrderCreateModel()->setShippingAsBilling(true);
    /* Just like adding products from Magento admin grid */
    if (!empty($data['add_products'])) {
        $this->_getOrderCreateModel()->addProducts($data['add_products']);
    }
    /* Collect shipping rates */
    $this->_getOrderCreateModel()->collectShippingRates();
    /* Add payment data */
    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    $this->_getOrderCreateModel()->initRuleData()->saveQuote();

    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    return $this;
}

}


Monday, February 17, 2014

How to send email in Magento and add custom template to it

While creating a local module you may sometimes required to add the send mail functionality on success of your task.
Below is the code and description on how to create a send mail and loading it with a custom template..
 
As my module is based on sending a mail on successfully creating a duplicate order. So I am adding my code in the model folder when the duplicate order is created.

Step1:
At location app/code/local/Namespace/Module/Model/order.php

Add the following code:
//Here I am passing the order object and a payment object as my requirements is to show the product and price details
 public function sendMail(Varien_Object $order, Varien_Object $paymentObj) {

        $email = $order->getCustomerEmail();
        $fName = $order->getCustomerFirstname();
        $lName = $order->getCustomerLastname();

        $customerNote = $order->getCustomerNote();
        $paymentmethod = $paymentObj->getMethod();
      
        try {

            $storeObj = Mage::getModel('core/store')->load($order->getStoreId());
            $customerEmailId = $email;
            $customerFName = $fName;
            $customerLName = $lName;

            //load the custom template to the email 
            $emailTemplate = Mage::getModel('core/email_template')
                    ->loadDefault('custom_template');
           
            // it depends on the template variables
            $emailTemplateVariables = array();
            $emailTemplateVariables['order'] = $order;
            $emailTemplateVariables['store'] = $storeObj;
            $emailTemplateVariables['payment_html'] = $method;
      

            $emailTemplate->setSenderName('Magento');
            $emailTemplate->setSenderEmail('sender.com');
            $emailTemplate->setType('html');
            $emailTemplate->setTemplateSubject('Add a subject');
            $emailTemplate->send($customerEmailId, $customerFName . $customerLName, $emailTemplateVariables);
            return true;
        } catch (Exception $e) {
            $errorMessage = $e->getMessage();
            return $errorMessage;
        }
    }
 
Step2:
At location app/code/local/Namespace/Module/etc/config.xml, add the following block of code
<config>
   <global>
       <template>
            <email>
                <custom_template  module="modulename">
                    <label>any desired  name</label>
                    <file>custom_template.html</file>  // this specifies the path where the custom template is located
                    <type>html</type>
                </custom_template>
            </email>
        </template>
     </global>
</config>
 
Step3:
At location app/locale/template/email/sales
Place your custom template file

Note: If your template file is at location app/locale/template/email, then in your config change the code:         <file>custom_template.html</file>