Tuesday, October 16, 2012

Change Position of bundle product option and custom options

<!--Additional block for bundle product type-->

    <
PRODUCT_TYPE_bundle>
        <
reference name="head">
            <
action method="addItem"><type>skin_js</type><name>js/bundle.js</name></action>
        </
reference>
        <
reference name="product.info">
            <
block type="bundle/catalog_product_view_type_bundle" name="product.info.bundle" as="product_type_data" after="-" template="bundle/catalog/product/view/type/bundle.phtml">
                <
action method="addPriceBlockType"><type>bundle</type><block>bundle/catalog_product_price</block><template>bundle/catalog/product/price.phtml</template></action>
                <
block type="bundle/catalog_product_price" name="bundle.prices" as="bundle_prices" template="bundle/catalog/product/view/price.phtml" />
            </
block>
        </
reference>

        <
reference name="product.info.options.wrapper">
            <
block type="bundle/catalog_product_view_type_bundle" name="product.info.bundle.options" as="type_bundle_options" after="-" template="bundle/catalog/product/view/type/bundle/options.phtml">
                <
action method="addRenderer"><type>select</type><block>bundle/catalog_product_view_type_bundle_option_select</block></action>
                <
action method="addRenderer"><type>multi</type><block>bundle/catalog_product_view_type_bundle_option_multi</block></action>
                <
action method="addRenderer"><type>radio</type><block>bundle/catalog_product_view_type_bundle_option_radio</block></action>
                <
action method="addRenderer"><type>checkbox</type><block>bundle/catalog_product_view_type_bundle_option_checkbox</block></action>
            </
block>
            <
action method="append"><block>product.info.bundle.options</block></action>
        </
reference>
        <
reference name="product.info.options.wrapper.bottom">
            <
remove name="product.tierprices" />
            <
block type="bundle/catalog_product_view" name="bundle.tierprices" as="tierprices" before="-" template="bundle/catalog/product/view/tierprices.phtml"/>
        </
reference>
        <
reference name="product.clone_prices">
            <
action method="addPriceBlockType"><type>bundle</type><block>bundle/catalog_product_price</block><template>bundle/catalog/product/view/price.phtml</template></action>
        </
reference>
    </
PRODUCT_TYPE_bundle>

Adding Confirm E-mail Address Field to Magento Frontend Forms

Adding Confirm E-mail Address Field to Magento Frontend Forms

If you are thinking of adding a confirmation of e-mail address to the front-end registration pages of your store e.g the Checkout billing page or the customer account registration, the little snippets below could be of use to you
For the Checkout billing page
1. Locate the magento checkout billing page (billing.phtml) which can be found in app/design/frontend/default/ /template/checkout/onepage
2. Add code 1 below where situable;
Code 1

<div class="field"><label for="billing:confirm_email" class="required"><em>*</em><?php echo $this->__('Confirm Email Address') ?></label>
<div class="input-box">
<input type="text" name="billing[confirm_email]" title="<?php echo $this->__('Confirm Email') ?>" id="billing:confirm_email" class="input-text required-entry validate-cemail" />
</div>
For the validation of this email confirmation field with the actual email field
3. Locate the Javascript file which Magento uses for validation (validation.js) in /js/prototype
4. Add code 3 where suitable e.g immediately after this line(code 2) in validation.js
Code 2
1
2
return !(pass.length < 7);
    }],
Code 3

['validate-cemail', 'Please make sure your emails match.', function(v) {
var conf = $$('.validate-cemail')[0];
var pass = false;
if ($('email')) {
pass = $('email');
}
var emailElements = $$('.validate-email');
for (var i = 0; i < emailElements.size(); i++) {
var emailElement = emailElements[i];
if (emailElement.up('form').id == conf.up('form').id) {
pass = emailElement;
}
}
if ($$('.validate-admin-email').size()) {
pass = $$('.validate-admin-email')[0];
}
return (pass.value == conf.value);
}],
Then that should just do exactly what you want.
For the Customer Account Registration page
1. Locate the magento account register page ,register.phtml in
app/design/frontend/ /default/template/persistent/customer/form/
2. Include code 4 where suitable
Code 4

<div class="field">
<label for="confirm_email" class="required"><em>*</em><?php echo $this->__('Confirm Email Address') ?></label>
<div class="input-box">
<input type="text" name="confirm_email" title="<?php echo $this->__('Confirm Email') ?>" id="confirm_email" class="input-text required-entry validate-cemail" />
</div>
</div>

Sunday, October 14, 2012

Tell a Friend in pop-up


Change the send a friend layout to popup


        <reference name="root">
           <action method="setTemplate"><template>page/popup.phtml</template></action>
        </reference>

 
Use this script in catalog page(id you are using colorbox)

   <?php if ($this->helper('customer')->isLoggedIn()): ?>
          <p class="email-friend"><a href="<?php echo $this->helper('catalog/product')->getEmailToFriendUrl($_product) ?>" rel="fancybox" class="group2 cboxElement"><?php echo $this->__('Email to a Friend') ?></a></p>
     <?php else: ?>
          <p class="email-friend"><a href="<?php echo $this->helper('catalog/product')->getEmailToFriendUrl($_product) ?>"><?php echo $this->__('Email to a Friend') ?></a></p>
     <?php endif; ?>
<?php endif; ?> 

Friday, October 12, 2012

Enable Custom option in bundle product


As a quick solution to add Custom Options to bundled products with dynamic prices you may try to tweak prepareProductSave method in app/code/core/Mage/Bundle/Model/Observer.php, namely just comment some code out as follows: 
/*
        if ($product->getPriceType() == '0' && !$product->getOptionsReadonly()) {
            $product->setCanSaveCustomOptions(true);
            if ($customOptions = $product->getProductOptions()) {
                foreach (array_keys($customOptions) as $key) {
                    $customOptions[$key]['is_delete'] = 1;
                }
                $product->setProductOptions($customOptions);
            }
        }
*/
To get rid of “Bundle with dynamic pricing cannot include custom defined options. Options will not be saved.” message you should hack app/design/adminhtml/default/default/template/catalog/product/edit/options.phtml template
//show error message
/*
if ($('price_type')) {
    if ($('price_type').value == '0' && $('dynamic-price-warrning')) {
        $('dynamic-price-warrning').show();
    }
}
*/

Tuesday, September 11, 2012

To add a new column to an existing table in the database In Magento

To add a new column to an existing table in the database, we will be dealing with 1 file and changing 2 database tables. In my example, I’m going to add a new column called my_new_column to the “Sales Order” object.
Let’s get started!
First open the following file:
  app/code/local/Mage/Sales/Model/Entity/Setup.php - This an array full of attributes to use to keep track of sale data
You’ll see something like this:
  public function getDefaultEntities(){
  
      return array(
          'quote'=>array(
              'entity_model'  => 'sales/quote',
              'table'         => 'sales/quote',
              'attributes' => array(
                  'entity_id'         => array('type'=>'static'),
                  'is_active'         => array('type'=>'static'),
                  'store_id'          => array('type'=>'static'),
         ...
          'order' => array(
              'entity_model'      => 'sales/order',
              'table'=>'sales/order', //The table name, in this case sales_order
              'increment_model'=>'eav/entity_increment_numeric',
              'increment_per_store'=>true,
              'backend_prefix'=>'sales_entity/order_attribute_backend',
              'attributes' => array(
                  'entity_id' => array(
                      'type'=>'static',
                     'backend'=>'sales_entity/order_attribute_backend_parent'
                  ),
                  'store_id'  => array('type'=>'static'),
                  'store_name' => array('type'=>'varchar'),
                  'remote_ip' => array(),
                  'status'    => array('type'=>'varchar'),
                  'state'     => array('type'=>'varchar'),
                  'hold_before_status' => array('type'=>'varchar'),
                  'hold_before_state'  => array('type'=>'varchar'),
                  'my_new_column'      => array('type'=>'static'),  //**Add this**
This file contains the variables each table should contain. Do a search for ‘table’⇒’ to find which file you’re dealing with. In my case I want to add it to the ‘sales_order’ table, so I’ll search for ‘sales/order’. I’ll simply add ‘my_new_column’ to the list below.
Now, our code is all set up and ready to rock. However, we still need to add this attribute to the eav_attribute table in your mysql database.
Log into your database and enter the 2 commands:
  alter table sales_order add my_new_column decimal(12,4) DEFAULT NULL;
  insert into eav_attribute('entity_type_id','attribute_code','attribute_model','backend_model','backend_type','backend_table','frontend_model','frontend_input','frontend_input_renderer','frontend_label','frontend_class','source_model','is_global','is_visible','is_required','is_user_defined','default_value','is_searchable','is_filterable','is_comparable','is_visible_on_front','is_html_allowed_on_front','is_unique','is_used_for_price_rules','is_filterable_in_search','used_in_product_listing','used_for_sort_by','is_configurable','apply_to','position','note','is_visible_in_advanced_search'  ) values(11, 'my_new_column', null, '', 'static', '', '', 'text', '','',null, '', 1,1,1,0,'',0,0,0,0,0,0,1,0,0,0,1,'',0,'',0);
Be sure to change ‘my_new_column’ to whatever name you’d like. In the alter table, be sure to set the appropriate column type. Remember, it’s varchar for strings.
And you’re finished!
Now to retrieve the data you call getMyNewColumn(). To save data to this column you call setMyNewColumn( $new_data_to_set ).

Monday, September 10, 2012

Create Custom Order Magento

Create Order

Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.

$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);
$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);
$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other
// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);
// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);
$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/
//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);
// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);
foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);
$subTotal += $rowTotal;
$order->addItem($orderItem);
}
$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);
$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();

Creating Customer

Below is a php code to create a customer account in magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__");a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';
    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);
    $customer->setConfirmation(null);
    $customer->save();
    echo $customer->getId();
}

Creating Invoice

Below is a php code to create invoice for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
  
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
  
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
  
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
  
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
  
}

Create Shipment

Below is a php code to create a shipment for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());       
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}

Creating Credit Memo

Below is a php code to create a credit memo for an order in magento.

$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();
         
        $service = Mage::getModel('sales/service_order', $order);
        
        $creditmemo = $service->prepareCreditmemo($data);
        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,
                min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();

Monday, September 3, 2012

Product sorting on Date

// app/code/core/Mage/Catalog/Model/Config.php
public function getAttributeUsedForSortByArray()
{
    $options = array(
        'position'  => Mage::helper('catalog')->__('Position'),

        // HERE IS OUR NEW OPTION
        'created_at' => Mage::helper('catalog')->__('Date')
    );
    foreach ($this->getAttributesUsedForSortBy() as $attribute) {
        /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
        $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
    }

    return $options;
}
 
It is not so easy, if you are not into modifying core files. In that case you must create this bunch of files:
app/etc/modules/Stackoverflow_Catalog.xml
<?xml version="1.0"?>
<config>
    <modules>
    <Stackoverflow_Catalog>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Catalog />
        </depends>
    </Stackoverflow_Catalog>
</modules>
</config>
app/code/local/Stackoverflow/Catalog/etc/config.xml
<?xml version="1.0"?>
<config>
<global>
    <models>
        <catalog>
            <rewrite>
                <config>Stackoverflow_Catalog_Model_Config</config>
            </rewrite>
        </catalog>
    </models>
</global>
 
app/code/local/Stackoverflow/Catalog/Model/Config.php
<?php
class Stackoverflow_Catalog_Model_Config extends Mage_Catalog_Model_Config {
public function getAttributeUsedForSortByArray()
{
    $options = parent::getAttributeUsedForSortByArray();
    if (!isset($options['created_at'])) {
        $options['created_at'] = Mage::helper('catalog')->__('Date');
    }
    return $options;
}
}