Tuesday 26 September 2017

Add Custom Field to Customer Address

$installer = Mage::getSingleton('eav/entity_setup', 'eav_setup');

$installer->startSetup();

$installer->addAttribute('customer_address', 'addresstyped', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Address Type',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'user_defined' => 1,
    'visible_on_front' => 1
));
Mage::getSingleton('eav/config')
    ->getAttribute('customer_address', 'addresstyped')
    ->setData('used_in_forms', array('customer_register_address','customer_address_edit','adminhtml_customer_address'))
    ->save();
$installer->endSetup();


Module created :-
1. Path :- /app/etc/modules/Dapl_Excellenceaddress.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Dapl_Excellenceaddress>
            <active>true</active>
            <codePool>local</codePool>
        </Dapl_Excellenceaddress>
    </modules>
</config>

2. Path:- /app/code/local/Dapl/Excellenceaddress/etc/config.xml

 <global>
                <fieldsets>
            <sales_convert_quote_address>
                <addresstyped>
                    <to_order_address>*</to_order_address>
                    <to_customer_address>*</to_customer_address>
                </addresstyped>
            </sales_convert_quote_address>
            <customer_address>
                <addresstyped>
                    <to_quote_address>*</to_quote_address>
                </addresstyped>
            </customer_address>
        </fieldsets>
 </global>

Next step:-
ALTER TABLE  `sales_flat_quote_address` ADD  `addresstyped` VARCHAR( 255 ) NOT NULL AFTER  `fax` ;

Text
Add {{depend addresstyped}}ID# {{var addresstyped}}{{/depend}} where ever you want it. {{depend}} basically checks, if govt_id is not empty.
Text One line
Add {{depend addresstyped}}ID# {{var addresstyped}}{{/depend}} where ever you want it. This format shows up in the checkout page shipping,billing address dropdowns.
HTML
Add {{depend addresstyped}}<br/>ID# {{var addresstyped}}{{/depend}}. This format is used in many places like Order View, Address Display etc.
PDF
Add {{depend addresstyped}}<br/>ID# {{var addresstyped}}{{/depend}}|. This format is used in PDF invoices, shipments etc.
Javascript Template
Add <br/>ID#{addresstyped}. This is used in admin add/edit address area.
After saving these in the configuration, the new address format should be visible. 

Wednesday 13 September 2017

Magento Custom Category Attribute File

1.Your category attribute installer:
$installer = $this;
$installer->startSetup();
$installer->addAttribute('catalog_category', 'custom_flv', array(
    'group'                    => 'General',
    'label'                    => 'Some File',
    'input'                    => 'image',
    'type'                     => 'varchar',
    'backend'                  => 'some_module/category_attribute_backend_file',
    'global'                   => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'                  => true,
    'required'                 => false,
    'user_defined'             => true,
    'order'                    => 20
));
$installer->endSetup();


2.\app\code\local\Some\Module\Model\Category\Attribute\Backend\File.php

class Some_Module_Model_Category_Attribute_Backend_File extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
    public function afterSave($object)
    {
        $value = $object->getData($this->getAttribute()->getName());

        if (is_array($value) && !empty($value['delete'])) {
            $object->setData($this->getAttribute()->getName(), '');
            $this->getAttribute()->getEntity()
                ->saveAttribute($object, $this->getAttribute()->getName());
            return;
        }

        $path = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
        try {
            $uploader = new Mage_Core_Model_File_Uploader($this->getAttribute()->getName());

            $uploader->setAllowedExtensions(array('flv','pdf','doc','txt','sql'));
            $uploader->setAllowRenameFiles(true);
            $result = $uploader->save($path);
            //allowed extensions here
            $object->setData($this->getAttribute()->getName(), $result['file']);
            $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
        } catch (Exception $e) {
            if ($e->getCode() != Mage_Core_Model_File_Uploader::TMP_NAME_EMPTY) {
                Mage::logException($e);
            }
            return;
        }
    }
}

3./app/code/local/Some/Module/etc/config.xml
<global>
    <resources>
        <some_module_setup>
            <setup>
                <module>Some_Module</module>
                <class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
            </setup>
        </some_module_setup>
    </resources>
    <!--another nodes -->
 </global>

Wednesday 23 August 2017

How to use WYSIWYG editor (TinyMCE) in custom Admin Magento Module

1> Including TincyMCE in Head
Add the following function in your Adminhtml Edit Class
(MagePsycho_Demomodule_Block_Adminhtml_Demomodule_Edit):

protected function _prepareLayout() {
    parent::_prepareLayout();
    if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
        $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
    }
}


2> Enabling in Form Field
Add the following content field in your Adminhtml Form class
(MagePsycho_Demomodule_Block_Adminhtml_Demomodule_Edit_Tab_Form):

$fieldset->addField('content', 'editor', array(
    'name'      => 'content',
    'label'     => Mage::helper('demomodule')->__('Content'),
    'title'     => Mage::helper('demomodule')->__('Content'),
    'style'     => 'height:15em',
    'config'    => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
    'wysiwyg'   => true,
    'required'  => false,
));

Thursday 8 June 2017

blur jQuery

jQuery(".qty").blur(function(){
  var currency_sy= jQuery('#currency_syamble').val();
  var qty_val = jQuery(this).val();
  var item_price = parseFloat(jQuery(this).attr('data-price'));
  var currency_sy = jQuery(this).attr('data-currency');
  var totalItemPrice = qty_val*item_price;
  var total_item = parseFloat(totalItemPrice).toFixed(2);
  jQuery(this).parent().find('.item_total_price').html(currency_sy+total_item);
  var Totalprice=0;
  jQuery(".qty-wrapper").each(function(index) {
      var eachQty = jQuery(this).find('.qty').val();
      var eachprice = jQuery(this).find('.qty').attr('data-price');
      Totalprice = Totalprice + (eachQty*eachprice);
     
  });
  var total = parseFloat(Totalprice).toFixed(2);

 
  jQuery("#total_price").html(currency_sy+total);
});

Removing an item from a select box JQuery

$("#selectBox option[value='option1']").remove();


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectBox" id="selectBox">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

Tuesday 16 May 2017

How to Add Custom Field to Customer Address in magento



$installer = new Mage_Eav_Model_Entity_Setup('core_setup');

$installer->startSetup();

$installer->addAttribute('customer_address', 'specialdeliveryins', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Special Delivery Instruction',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'user_defined' => 1,
    'visible_on_front' => 1
));
Mage::getSingleton('eav/config')
    ->getAttribute('customer_address', 'specialdeliveryins')
    ->setData('used_in_forms', array('customer_register_address','customer_address_edit','adminhtml_customer_address'))
    ->save();
$installer->endSetup(); 

Thursday 11 May 2017

How to add a custom image field to a category in Magento?

Step:1. At first run this code  
 $installer = new Mage_Eav_Model_Entity_Setup('core_setup');
    $installer->startSetup();
    $attribute  = array(
    'type'          =>  'text',
    'label'         =>  'Banner Image',
    'input'         =>  'image',
    'global'        =>  Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'visible'       =>  true,
    'required'      =>  false,
    'backend'       => 'catalog/category_attribute_backend_image',
    'user_defined'  =>  true,
    'default'       =>  "",
    'group'         =>  "General Information"
    );
    $installer->addAttribute('catalog_category', 'banner_image', $attribute);
    $installer->endSetup();



Step 2:
Copy Category.php file from app/code/core/Mage/Catalog/Model/Category.php
to
 app/code/local/Mage/Catalog/Model/Category.php

Add this code line 480
 public function getBannerImageUrl()
    {
        $url = false;
        if ($image = $this->getBannerImage()) {
            $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
        }
        return $url;
    }

Friday 5 May 2017

How to add custom property to magento Attributes?

Step 1: At first run this code.
<?php
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$installer->getConnection()->addColumn(
    $installer->getTable('catalog/eav_attribute'),
    'comment',
    array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'comment'   => 'Comment'
    )
);
$installer->endSetup(); ?>


Step 2:
Then add this code.
/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php

       $fieldset->addField('comment', 'textarea', array(
            'name' => 'comment',
            'label' => Mage::helper('catalog')->__('Comment'),
            'title' => Mage::helper('catalog')->__('Comment'),
            'note' => Mage::helper('catalog')->__('Comment'),
           
        ));

Thursday 4 May 2017

How to create a different product page structure for specific products in magento?



<reference name="product.info">
<action method="setTemplate">
<template>catalog/product/view-recipe.phtml</template>
</action>
</reference>
Step 1 :-  Admin => Catalog => Manage Product => Select this specific products => Left design section => Custom Layout Update (Add this above code)

Step 2 :- Then "view-recipe.phtml" upload the file this path
app/design/frontend/rwd/theme name/template/catalog/product/

Wednesday 3 May 2017

programmatically order create in magento

<?php
    error_reporting(0);  
    require_once 'app/Mage.php';
    umask(0);
    Mage::app();  
   
    $row = 1;
    $line_flag = true;
   
    if (($handle = fopen("test.csv", "r")) !== FALSE)
    {
$flag=0;
$arr_row=array();

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
   if($line_flag)
   {
$line_flag = false;
continue;
   }
 
   $current_order_no=$data[1];
 
   $product_name=$data[4];
   $product_sku=$data[5];
   $product_price=$data[9];
 
   $customer_id=$data[12];
 
   $SKU = $product_sku;
   $productid = Mage::getModel('catalog/product')->getIdBySku(trim($SKU));

   $product = Mage::getModel('catalog/product');
   $product ->load($productid);
   $prod=$product->getData();
 
   $product_id = $product->getId();
 
   //if the product is not found in the db code start to add product
 
   if(count($prod)<=5)
   {
//echo "not ext";

$data=array("weight"=>"10","sku"=>$SKU,"name"=>$product_name,"description"=>"description","sdesc"=>"sdesc","price"=>$product_price,"cid"=>"2");

$newproduct = new Mage_Catalog_Model_Product();
$newproduct->setTypeId('simple');
$newproduct->setWeight($data['weight']);
$newproduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$newproduct->setStatus(1);
$newproduct->setSku($data['sku']);
$newproduct->setTaxClassId(0);
$newproduct->setCategoryIds($data['cid']);

$newproduct->setWebsiteIDs(array(1));
$newproduct->setStoreIDs(array(1));
$newproduct->setStockData(array(
'is_in_stock' => 1,
'qty' => 199,
'manage_stock' => 1
));
$newproduct->setAttributeSetId(4);
$newproduct->setName($data['name']);
//$newproduct->setCategoryIds(array(3)); // array of categories it will relate to
$newproduct->setDescription($data['description']);
$newproduct->setShortDescription($data['sdesc']);
$newproduct->setPrice($data['price']);
$newproduct->save();

$product_id = $newproduct->getId();
   }
 
   $customer = Mage::getModel('customer/customer')->load($customer_id); // Customer Id  
   $customer_details=$customer->getData();
     
   $customerAddress = array();
   #loop to create the array
   foreach ($customer->getAddresses() as $address)
   {
      $customerAddress[] = $address->toArray();
   }
   #displaying the array
   //echo '<pre/>';print_r($customerAddress );exit;
 
 
   $firstname=$customer_details['firstname'];
   $lastname=$customer_details['lastname'];
   $company=$customer_details['lastname'];
   $email=$customer_details['email'];
 
   $street=$customerAddress[0]['street'];
   $city=$customerAddress[0]['city'];
   $region_id=$customerAddress[0]['region_id'];
   $region=$customerAddress[0]['region'];
   $postcode=$customerAddress[0]['postcode'];
   $country_id=$customerAddress[0]['country_id'];
   $telephone=$customerAddress[0]['telephone'];
   $fax=$customerAddress[0]['fax'];
 
   $customer_password='';
   $confirm_password='';
 
   $save_in_address_book='0';
   $use_for_shipping='1';
 
 
   $productId=$product_id;
   $store=Mage::app()->getStore();
 
   // Start New Sales Order Quote
   $quote=Mage::getModel('sales/quote')->setStoreId($store->getId());

 
   //Customer Billing Address Data

   $billingAddress = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => 'Test',
'email' =>  $email,
'street' => $street,
'city' => $city,
'region_id' => $region_id,
'region' => $region,
'postcode' => $postcode,
'country_id' => $country_id,
'telephone' =>  $telephone,
'fax' => $fax,
'customer_password' => '',
'confirm_password' =>  '',
'save_in_address_book' => '0',
'use_for_shipping' => '1',
   );
 
 
    //Customer Shipping Address Data
       
   $shippingAddress = array(
'firstname' => $firstname,
'lastname' => $lastname,
'street' => $street,
'city' => $city,
'region' => $region,
'region_id' => $region_id,
'postcode' => $postcode,
'country_id' => $country_id,
'telephone' => $telephone,
   );
     
 
   //$quote      = Mage::getModel('sales/quote')->setStoreId($store->getId());
 
   $quote=Mage::getModel('sales/quote')->setStoreId(1);
 
 
   
   //Load Product and add to cart
   $product_cart=Mage::getModel('catalog/product')->load($productId);  
   $buyInfo=array('qty' => 1);  
   $quote->addProduct($product_cart, new Varien_Object($buyInfo));


   // Add Billing Address
   $quote->getBillingAddress()
   ->addData($billingAddress);

 
   //Add Shipping Address and set shipping method  
   $quote->getShippingAddress()
   ->addData($shippingAddress)      
   ->setCollectShippingRates(true)
   ->setShippingMethod('freeshipping_freeshipping')
   ->setCouponCode('test')
   ->collectTotals();
       $quote->setCouponCode('test');
   $quote->collectTotals()->save();

   /*

   //Set Customer group As Guest    
   $quote->setCheckoutMethod('guest')
->setCustomerId(null)
->setCustomerEmail($quote->getBillingAddress()->getEmail())
->setCustomerIsGuest(true)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
*/
 
$quote->setCustomerId($customer_id)
        ->setCustomerEmail($email)
        ->setCustomerIsGuest(false)
        ->setCustomerGroupId(1);


   //Set Payment method
 
   $quote->getPayment()->importData(array('method' => 'cashondelivery'));
   $quote->collectTotals()->save();


   //Save Order With All details




   $service = Mage::getModel('sales/service_quote', $quote);
   $service->submitAll();
   $increment_id = $service->getOrder()->getIncrementId();
 
 
 
   Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "1");
 
   //Send Order Mail
 
   $order_mail = new Mage_Sales_Model_Order();
   $order_mail->loadByIncrementId($increment_id);
   $order_mail->sendNewOrderEmail();
 
   //echo $increment_id;

   /*  For Invoice start */


   $order=Mage::getModel("sales/order")->loadByIncrementId($increment_id);
   //Mage::getModel("sales/order")->loadByIncrementId($incrementId);


   $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
   $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
   $invoice->register();
   $transaction = Mage::getModel('core/resource_transaction')
    ->addObject($invoice)
   ->addObject($invoice->getOrder());
   $transaction->save();
   if($order->canShip()):
$itemQty =  $order->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($increment_id);
endif;
   $order->setData('state',"complete");
   $order->setStatus("complete");
 
   //$history = $order->addStatusHistoryComment('Order marked as complete automatically.',false);
 
   $history = $order->addStatusHistoryComment('Order Number: '.$current_order_no);
 
 
   $history->setIsCustomerNotified(false);
   $order->save();
   $id=$order->getId();


/* --------  End --------------------------------------------------- */
 
 
}

fclose($handle);

    }
    else
    {
echo "no file found";
    }
?>

Wednesday 1 March 2017

Magento get Sale Products

<?php
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->addAttributeToSelect(array(
                                   'image',
                                   'name',
                                   'short_description'
                   ))
                   ->addFieldToFilter('visibility', array(
                               Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                               Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                   )) //showing just products visible in catalog or both search and catalog
                   ->addFinalPrice()
//                        ->addAttributeToSort('price', 'asc') //in case we would like to sort products by price
                   ->getSelect()
                   ->where('price_index.final_price < price_index.price')
//                        ->limit(30) //we can specify how many products we want to show on this page
//                        ->order(new Zend_Db_Expr('RAND()')) //in case we would like to sort products randomly
                   ;

Mage::getModel('review/review')->appendSummary($_productCollection);

$_helper = $this->helper('catalog/output');
?>
//
<?php if(!$_productCollection->count()): ?>
    <p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
    <div class="category-products">
        <?php // List mode ?>
            <?php $_iterator = 0; ?>
            <ol class="products-list" id="products-list">
                <?php foreach ($_productCollection as $_product): ?>
                    <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                        <?php // Product Image ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $_product->getImageUrl(); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
                        <?php // Product description ?>
                        <div class="product-shop">
                            <div class="f-fix">
                                <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                                <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                                <?php if($_product->getRatingSummary()): ?>
                                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                                <?php endif; ?>
                                <?php echo $this->getPriceHtml($_product, true) ?>
                                <?php if($_product->isSaleable()): ?>
                                    <p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
                                <?php else: ?>
                                    <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                                <?php endif; ?>
                                <div class="desc std">
                                    <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                                </div>
                                <ul class="add-to-links" style="margin:0; padding-left:0; list-style: none;">
                                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                                    <?php endif; ?>
                                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                                        <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                                    <?php endif; ?>
                                </ul>
                            </div>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ol>
            <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
    </div>
<?php endif; ?>

Tuesday 17 January 2017

Get City Country By IP Address in PHP

/*Get user ip address*/
$ip_address=$_SERVER['REMOTE_ADDR'];

/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ip_address;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));

/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];

/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];

/*Comment out these line to see all the posible details*/
/*echo '<pre>';
print_r($addrDetailsArr);
die();*/

if(!$city){
   $city='Not Define';
}if(!$country){
   $country='Not Define';
}
echo '<strong>IP Address</strong>:- '.$ip_address.'<br/>';
echo '<strong>City</strong>:- '.$city.'<br/>';
echo '<strong>Country</strong>:- '.$country.'<br/>';

Monday 16 January 2017

 Step 1:
Disable Magento Cache from magento back-end.

Just copy paste the below code in header.phtml and run yourmagento once, your attribute will be created and you can see in backend under manage category. Please remove this code once new attribute added.
$setup = new Mage_Eav_Model_Entity_Setup(‘core_setup’);

$setup->addAttribute(‘catalog_category’, ‘sliderimage’, array(
‘group’ => ‘General’,
‘input’ => ‘image’,
‘type’ => ‘varchar’,
‘label’ => ‘Slider Image’,
‘backend’ => ‘catalog/category_attribute_backend_image’,
‘visible’ => 1,
‘required’ => 0,
‘user_defined’ => 1,
‘global’ => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

Step 2:
Copy Category.php file from app/code/core/Mage/Catalog/Model/Category.php to app/code/local/Mage/Catalog/Model/Category.php
Step 3:
Open app/code/local/Mage/Catalog/Model/Category.php and find text “public function getImageUrl()” and insert below code to create new function for new image attribute to get it’s value with full URL.

Here BannerImage is attribute code:

public function getBannerImageUrl()
{
$url = false;
if ($image = $this->getBannerimage()) {
$url = Mage::getBaseUrl(‘media’).’catalog/category/’.$image;
}
return $url;
}


Step 4:
To call new category image attribute in category view page, please open app/design/frontend/default/YOURTHEMEFOLDER/template/catalog/category/view.phtml
You will get new image attribute with below code: getBannerImageUrl() function name as created above.

$_category->getBannerImageUrl();