Sunday, October 23, 2016

Add Order Details Column in Customer Grid Magento


Many Magento website used for e-commerce website and for store owner customers are most important for any website. so they check all customer details who is online and who purchase maximum orders from the website. So store admin analysis stores customer for any offers or selling orders.
So here display basic code that you can overwrite exiting core block grid using new extension or you can directly customize admin customer grid using some code display here.
First open 'app/code/core/Mage/Adminhtml/Block/Customer/Grid.php' file or you can copy that file on local pool and than customize it. find function `_prepareCollection()` change code as below.

protected function _prepareCollection()
{
        $collection = Mage::getResourceModel('customer/customer_collection')
            ->addNameToSelect()
            ->addAttributeToSelect('email')
            ->addAttributeToSelect('created_at')
            ->addAttributeToSelect('group_id')
            ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
            ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
            ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
            ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
            ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');
  //Add below code for last order date
        $sql ='SELECT MAX(o.created_at) FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order').' AS o WHERE o.customer_id = e.entity_id';
  $expr = new Zend_Db_Expr('(' . $sql . ')');
  $collection->getSelect()->from(null, array('last_order_date'=>$expr));
  //Add below code for count total orders
  $sql ='SELECT COUNT(*) FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order').' AS o WHERE o.customer_id = e.entity_id';
  $expr = new Zend_Db_Expr('(' . $sql . ')');
  $collection->getSelect()->from(null, array('orders_count'=>$expr));
  $this->setCollection($collection);
        return parent::_prepareCollection();
}

As below code you get the last order date and total customers orders from order table. In Magento `sales_flat_order` there is column for `customer_id` which is stored register customer id of that store.
Add below two fields in function `_prepareColumns ()` where you want to display fields.

$this->addColumn('last_order_date', array(
 'header'    => Mage::helper('customer')->__('Last Order Date'),
 'type'      => 'datetime',
 'align'     => 'center',
 'index'     => 'last_order_date',
 'filter'    => false, //For remove search column
 'sortable'  => false, //For remove sorting column
));
$this->addColumn('orders_count', array(
 'header'    => Mage::helper('customer')->__('Orders Count'),
 'index'     => 'orders_count',
 'type'  => 'number',
));
In below code you can use any `type` for show in grid and if you remove sorting and filtering functionality for this column than it's OK but if you want to short and filter of below column than you must create custom grid filter as below.

$this->addColumn('last_order_date', array(
 'header'    => Mage::helper('customer')->__('Last Order Date'),
 'type'      => 'datetime',
 'align'     => 'center',
 'index'     => 'last_order_date',
 'filter_condition_callback' => array($this, '_orderfiltersearch')
));
Than create new function on same file for search call callback function as below.

public function _orderfiltersearch($collection, $column)
{
 if (!$value = $column->getFilter()->getValue()){
  return $this;
 }
 if($value['orig_from'] == '' || $value['orig_to'] == ''){
  return $this;
 }
 $fromDate = date('Y-m-d H:i:s', strtotime($value['orig_from']));
 $toDate = date('Y-m-d H:i:s', strtotime($value['orig_to']));
 $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('created_at', array('from'=>$fromDate, 'to'=>$toDate));
 foreach($orders as $order)
 {
  $customerids[] = $order->getCustomerId();
 }
 $customerids = array_unique($customerids);
 $this->getCollection()->addFieldToFilter('entity_id', array('in' => $customerids));
 return;
}
You can use same search callback function for, finding others with getting order collection from the database according to customer id and use that id in `addFieldToFilter` for filter Magento collection.

Thursday, October 13, 2016

Remove Review Page in Magento PayPal Express Checkout


Magento is most used PHP based e-commerce platform which is used for create shopping website and for that payment system is most important part of any e-commerce system. Magento also provide some most used payment methods like PayPal, Authorized, COD, Check payment also also many extensions available for easy implement new payment method in website.
When you use the PayPal payment method than mostly used 'PayPal Express Checkout' for fast, secure and easy checkout. but after complete PayPal checkout it's redirecting to Magento payment review page.
If you use 'PayPal standard checkout' them after complete payment from PayPal, it's redirecting to a checkout success page and if your Magento version is greater than 1.9 than you can skin review page from the admin panel by set `Skip Order Review Step` YES.
If your Magento version is less than 1.9 than you can skin that page after changes on below files.
First open `app\code\core\Mage\Paypal\Model\Config.php` file and changes below in getExpressCheckoutStartUrl function from

public function getExpressCheckoutStartUrl($token)
{
    return $this->getPaypalUrl(array(
        'cmd'   => '_express-checkout',
        'token' => $token,
    ));
}
to
public function getExpressCheckoutStartUrl($token)
{
    return $this->getPaypalUrl(array(
        'cmd'   => '_express-checkout',
        'useraction' => 'commit',
        'token' => $token,
    ));
}
 
Than create observe event in global scope as below in any custom extension's `confix.xml` file or create own.
 
<controller_action_predispatch_paypal_express_review>
  <observers>
    <newsinfo_removepaypalexpressreview>
      <type>singleton</type>
      <class>Newsinfo_Modulename_Model_Observer</class>
      <method>controllerPaypalExpressReview</method>
    </newsinfo_removepaypalexpressreview>
  </observers>
</controller_action_predispatch_paypal_express_review>
<controller_action_predispatch_paypal_express_placeOrder>
  <observers>
    <newsinfo_removepaypalexpressreview>
      <type>singleton</type>
      <class>Newsinfo_Modulename_Model_Observer</class>
      <method>controllerPaypalExpressPlaceOrder</method>
    </newsinfo_removepaypalexpressreview>
  </observers>
</controller_action_predispatch_paypal_express_placeOrder>

Than create 'Observer.php' file in Model folder and add below code(You put below functions in exiting Observe.php file)

class Newsinfo_Modulename_Model_Observer //Set Class According to Your Extension
{
 public function controllerPaypalExpressReview(Varien_Event_Observer $observer)
 {
  Mage::app()->getResponse()->setRedirect(Mage::getUrl('*/*/placeOrder'));
 }
 public function controllerPaypalExpressPlaceOrder(Varien_Event_Observer $observer)
 {
  $agreements = Mage::helper('checkout')->getRequiredAgreementIds();
  $postagreements = array_fill_keys($agreements, 1);
  Mage::app()->getRequest()->setPost('agreement', $postagreements);
 }
}

Sunday, August 21, 2016

Solve WIFI Problem in Windows 10

Many users fetch WI-Fi problem in window 10 after upgrade from window to older version or install new window 10.So here describe some steps for solve WI-Fi problem on window 10.
If you are looking for any solution from below
  • No WiFi is available on my computer after Windows 10 update.
  • Windows 10 WI-Fi is not working.
  • How to connect Window 10 laptop with WI-Fi.
  • WI-Fi working solve after updating window 10.
  • Window 10 WI-Fi limited connectivity.
  • No WiFi adapter found after Windows 10 upgrade.

First why this occurs after updating window 10. It's because of WiFi driver not installed on window or old driver not compatible with Windows 10

Here below describe some steps for all users so apply any steps and than restart your PC and check again if not solve than check next step.
  1.  There are many software available in site like as "Driver Talent" to find missing driver in system but all software are paid for installed driver.
  2.  Run command prompt as administrator from Window+R key and write following command
    reg delete HKCR\CLSID\{988248f3-a1ad-49bf-9170-676cbbc36ba3} /va /f
    and than press YES and enter netcfg -v -u dni_dne command.
  3.  Press "Windows Key + S" and choose "Power Options". Locate the current plan of your computer ("Balanced") and click "Change plan settings"
    Click "Change advanced power settings"click "Apply", and then click "OK" choose "Maximum Performance" under "Wireless Adapter settings".
  4.  Open command prompt with admin rights and open below command
    netsh int ip reset 
  5. Open Network and Sharing Center from Control Panel than click on change adapter settings.Right click on WiFi and click properties than click on Configure Button.
    Navigate to last tab Power Management and select checkbox Allow the computer to turn off this device to save power click on OK
  6. Resetting Tcp/Ip Auto-tuning.Open command prompt as administrator from Window+R key.Type below commands one by one
    netsh int tcp set heuristics disabled
    netsh int tcp set global autotuninglevel=disabled
    netsh int tcp set global rss=enabled
  7. Open Device Manager from control panel or directly search from task bar.than click on Network Adapters and find your wireless driver
    Right click on it and choose first option Update Driver Software. Find driver from internet and install it.
  8. Find your laptop model driver from online and install it on PC.Open Device Manager and choose WiFi Driver from Network Adapter than click on "Browse my computer for driver software"
    than click on Let me pick from my computer.check show compatible hardware.select driver and click on next

Saturday, May 14, 2016

Delete all Sample Data in Magento 1.x

Magento used ORM structure for developing e-commerce website so it's faster and easier to fetch and manage data from database. so Magento also stores some unnecessary data which is not much useful for store so you can remove that from the database. Here to display the SQL queries that run in your mysql database. It's only remove junk data not effects on the site..
Here below also provide some other SQL queries for deleting products, orders and users. In below all examples use Magento database without any table prefix.If your database table has any prefix than writes table query as prefix..

Remove Magento junk and unnecessary data from Database

SET FOREIGN_KEY_CHECKS = 0; //Use for ignore foreign key if any.
-- Compare
TRUNCATE `catalog_compare_item`;

-- Wishlist
TRUNCATE `wishlist_item_option`;
TRUNCATE `wishlist_item`;
TRUNCATE `wishlist`;

-- Admin notification
TRUNCATE `adminnotification_inbox`;

-- Dataflow
TRUNCATE `dataflow_batch_export`;
TRUNCATE `dataflow_batch_import`;

-- Report
TRUNCATE `report_event`;
TRUNCATE `report_viewed_product_index`;
TRUNCATE `report_compared_product_index`;

-- Search
TRUNCATE `catalogsearch_fulltext`;
TRUNCATE `catalogsearch_query`;
TRUNCATE `catalogsearch_result`;

-- FLAT CATALOG (EDIT TABLE NAMES)
TRUNCATE `catalog_category_flat_store_1`;
TRUNCATE `catalog_product_flat_1`;

-- Logs
TRUNCATE `log_customer`;
TRUNCATE `log_quote`;
TRUNCATE `log_summary`;
TRUNCATE `log_summary_type`;
TRUNCATE `log_url`;
TRUNCATE `log_url_info`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;
TRUNCATE `log_visitor_online`;

-- Session
TRUNCATE `core_session`;
TRUNCATE `api_session`;

-- Cache
TRUNCATE `core_cache`;
TRUNCATE `core_cache_option`;
TRUNCATE `core_cache_tag`;

-- Index
TRUNCATE `index_event`;
TRUNCATE `index_process_event`;

-- Captcha
TRUNCATE `captcha_log`;

-- Sent to friend
TRUNCATE `sendfriend_log`;

-- Temp and index tables
TRUNCATE `catalog_category_anc_categs_index_tmp`;
TRUNCATE `catalog_category_anc_products_index_tmp`;
TRUNCATE `catalog_category_product_index_enbl_tmp`;
TRUNCATE `catalog_product_index_eav_decimal_tmp`;
TRUNCATE `catalog_product_index_eav_tmp`;
TRUNCATE `catalog_product_index_price_bundle_opt_tmp`;
TRUNCATE `catalog_product_index_price_bundle_sel_tmp`;
TRUNCATE `catalog_product_index_price_bundle_tmp`;
TRUNCATE `catalog_product_index_price_cfg_opt_agr_tmp`;
TRUNCATE `catalog_product_index_price_cfg_opt_tmp`;
TRUNCATE `catalog_product_index_price_downlod_tmp`;
TRUNCATE `catalog_product_index_price_final_tmp`;
TRUNCATE `catalog_product_index_price_opt_agr_tmp`;
TRUNCATE `catalog_product_index_price_opt_tmp`;
TRUNCATE `catalog_product_index_price_tmp`;
TRUNCATE `cataloginventory_stock_status_tmp`;
TRUNCATE `catalog_category_anc_categs_index_idx`;
TRUNCATE `catalog_category_anc_products_index_idx`;
TRUNCATE `catalog_category_product_index_enbl_idx`;
TRUNCATE `catalog_category_product_index_idx`;
TRUNCATE `catalog_product_index_eav_decimal_idx`;
TRUNCATE `catalog_product_index_eav_idx`;
TRUNCATE `catalog_product_index_price_bundle_idx`;
TRUNCATE `catalog_product_index_price_bundle_opt_idx`;
TRUNCATE `catalog_product_index_price_bundle_sel_idx`;
TRUNCATE `catalog_product_index_price_cfg_opt_agr_idx`;
TRUNCATE `catalog_product_index_price_cfg_opt_idx`;
TRUNCATE `catalog_product_index_price_downlod_idx`;
TRUNCATE `catalog_product_index_price_final_idx`;
TRUNCATE `catalog_product_index_price_idx`;
TRUNCATE `catalog_product_index_price_opt_agr_idx`;
TRUNCATE `catalog_product_index_price_opt_idx`;
TRUNCATE `cataloginventory_stock_status_idx`;
 
SET FOREIGN_KEY_CHECKS = 1; 

Remove Magento all 'Products' from Database


SET FOREIGN_KEY_CHECKS = 0; 

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock`;
TRUNCATE TABLE `rating_option_vote`; 
TRUNCATE TABLE `rating_option_vote_aggregated`;
TRUNCATE TABLE `review`; 
TRUNCATE TABLE `review_detail`; 
TRUNCATE TABLE `review_entity_summary`; 
TRUNCATE TABLE `review_store`;

INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
TRUNCATE TABLE `catalog_product_entity`;

SET FOREIGN_KEY_CHECKS = 1;

Remove Magento all 'Categories' from Database

SET FOREIGN_KEY_CHECKS = 0; 

TRUNCATE TABLE `catalog_category_entity`;
TRUNCATE TABLE `catalog_category_entity_datetime`;
TRUNCATE TABLE `catalog_category_entity_decimal`;
TRUNCATE TABLE `catalog_category_entity_int`;
TRUNCATE TABLE `catalog_category_entity_text`;
TRUNCATE TABLE `catalog_category_entity_varchar`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;

INSERT  INTO `catalog_category_entity`(`entity_id`,`entity_type_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`POSITION`,`level`,`children_count`) VALUES (1,3,0,0,'0000-00-00 00:00:00','2009-02-20 00:25:34','1',1,0,1),(2,3,3,0,'2009-02-20 00:25:34','2009-02-20 00:25:34','1/2',1,1,0);
INSERT  INTO `catalog_category_entity_int`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,32,0,2,1),(2,3,32,1,2,1);
INSERT  INTO `catalog_category_entity_varchar`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,31,0,1,'Root Catalog'),(2,3,33,0,1,'root-catalog'),(3,3,31,0,2,'Default Category'),(4,3,39,0,2,'PRODUCTS'),(5,3,33,0,2,'default-category');

SET FOREIGN_KEY_CHECKS = 1;

Remove Magento all 'Customers' from Database

SET FOREIGN_KEY_CHECKS = 0; 

TRUNCATE `customer_address_entity`;
TRUNCATE `customer_address_entity_datetime`;
TRUNCATE `customer_address_entity_decimal`;
TRUNCATE `customer_address_entity_int`;
TRUNCATE `customer_address_entity_text`;
TRUNCATE `customer_address_entity_varchar`;
TRUNCATE `customer_entity`;
TRUNCATE `customer_entity_datetime`;
TRUNCATE `customer_entity_decimal`;
TRUNCATE `customer_entity_int`;
TRUNCATE `customer_entity_text`;
TRUNCATE `customer_entity_varchar`;

SET FOREIGN_KEY_CHECKS = 1;

Remove Magento all 'Orders' from Database

SET FOREIGN_KEY_CHECKS = 0; 

TRUNCATE `sales_order`;
TRUNCATE `sales_order_datetime`;
TRUNCATE `sales_order_decimal`;
TRUNCATE `sales_order_entity`;
TRUNCATE `sales_order_entity_datetime`;
TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
TRUNCATE `sales_order_int`;
TRUNCATE `sales_order_text`;
TRUNCATE `sales_order_varchar`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_item`;

SET FOREIGN_KEY_CHECKS = 1;

Tuesday, May 10, 2016

Install ElasticSearch on Window(wamp) Server

Elasticsearch is an open-source search server based on Lucene. It provides a broadly-distributed, readily-scalable, multitenant-capable full-text search engine with an HTTP web interface as JSON schema documents. Elasticsearch can power extremely fast searches that support your data discovery applications.
ElasticSearch  is mostly use for searching functionality implementation first it's store huge data as local storage and than after give data according to our search as JSON format.It's easy to use so mostly people use this for faster search functionality.
For installation of ElasticSearch with PHP based application than it's some complicated for installation in window server. Here describe simple and basic steps of the installation process of ElasticSearch.
  • First download ElasticSearch latest version from Here
  • Than after download Zip or Tar file package.
  • First check in your system java is installed or not.for that open cmd and write `java -version` that display version if installed.
  • If not installed than find latest version of Java from Here and install into your system.
  • Set new "Environment Variables" path as 'JAVA_HOME' and path 'C:\Program Files\Java\jre1.8.0_77' (Where you install java).
  • Extract all files of ElasticSearch downloaded from site to system drive.
  • Now open 'elasticsearch.bat' file in 'C:\elasticsearch-2.3.2\bin\' directory.
  • If there is any error than it's display otherwise it's execute all process. 
  • After complete all process don't close it.Now open http://localhost:9200
  • It's display  ElasticSearch information.
For use ElasticSearch in PHP based application download from Here and follow steps describe there and also describe basic exampled for how to use.Install elastic search in PHP through Composer.
If you want to install  ElasticSearch on live server than follow Here.and must set `elasticsearch.yml` file(in C:\elasticsearch-2.3.2\config\ folder) variable according to server.

Saturday, May 7, 2016

Set Custom Order Increment id in Magento

Magento is most uses PHP based platform for e-commerce website. In Magento website adds products from admin panel and in front any user buy that product and after complete payment method or check out it's generated new order in the Magento database with unique order id.In default Magento order id(as increment id) starts from '100000001' and then after increment one for the next order.
Magento all orders saves in sales_flat_order table with unique entity_id as primary key. so you can get order information by order entity id or increment value. In order table entity_id is the primary key so you can't modify it. but you can change the order increment id that displays also in fronted.
When you want to develop a website and want to change the increment id that from a database you can change the order increment id prefix only. for that use below SQL query in your MySql command.


UPDATE `eav_entity_store` SET `increment_prefix` = 'NEWS-' WHERE `entity_store_id` = '1' AND `entity_type_id` = '5'

Here you can add own prefix in `increment_prefix` column.`entity_store_id` is your store id and `entity_type_id` is order type(different for invoice,shipment).
Sometimes you want to change the order increment id not only prefix or want to add a different prefix using some condition then you must change in core Magento files with creating a simple module as below.
First create new Newsinfo_Order.xml file in app/etc/modules/ as below.

<config>
  <modules>
    <newsinfo_order>
      <active>true</active>
      <codepool>local</codepool>
    </newsinfo_order>
  </modules>
</config>
 
Than create new config.xml file in app/code/local/Newsinfo/Order/etc/ as below.

<?xml version="1.0"?>
<config>
  <modules>
    <Newsinfo_Order>
      <version>1.0.0</version>
    </Newsinfo_Order>
  </modules>
  <global>
    <models>
      <sales>
        <rewrite>
          <order>Newsinfo_Order_Model_Order</order>
        </rewrite>
      </sales>
    </models>
  </global>
</config>
 
Here in below file just rewrite magento 'Mage_Sales_Model_Order' model with custom extension or you can directly changes in core file from app/code/core/Mage/Sales/Model/Order.php
Than after create new model file in app\code\local\Newsinfo\Order\Model named Order.php with below code. 

class Newsinfo_Order_Model_Order extends Mage_Sales_Model_Order 
{
 protected function _beforeSave()
 {
  parent::_beforeSave();
  $this->_checkState();
  $this->setIncrementId('NEWSINFO-'.$this->getIncrementId());
  return $this;
 }
}
Here below function you can change your order prefix and also add some condition for different prefix or dynamic prefix or order increment id.order increment id is unique value so here must use unique value otherwise order not created.

Add Layered Navigation to Advance Search Result Page in Magento


Magento Layered Navigation is used for search products according to categorize, price or different attribute which are assigned from Magento admin panel. So when users want to product by color, size than they can using Layered Navigation.
In Magento Layered Navigation display in left side of each category listing page if there are some products in category. It's also display in the left side column in search results page. Layered Navigation is auto generated according to a listing of products. if all products on listings attribute price and category are same then it's not displayed.
You can call layer navigation block on category listing page using catalog.xml file with below code.

<reference name="left">
  <block type="catalog/layer_view" name="catalog.leftnav" before="-" template="catalog/layer/view.phtml"/>
</reference>

That's define according to anchor and non anchor category in Magento.But it's not display in advance search results.so here describe simple way for display Layered Navigation in advance search result page by modifying core Magento file or you can rewrite that using custom module.
Change prepareProductCollection function as below in app/code/core/Mage/CatalogSearch/Model/Layer.php file.

public function prepareProductCollection($collection)
{
    if(Mage::helper('catalogsearch')->getQuery()->getQueryText())
    {
        $collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
        ->addSearchFilter(Mage::helper('catalogsearch')->getQuery()->getQueryText())
        ->setStore(Mage::app()->getStore())
        ->addMinimalPrice()
        ->addFinalPrice()
        ->addTaxPercents()
        ->addStoreFilter()
        ->addUrlRewrite();
    }
    else
    {
        $collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes());
        $attributes = Mage::getSingleton('catalog/product')->getAttributes();
        foreach($attributes as $attribute)
        {
            $attribute_code = $attribute->getAttributeCode();
            if($attribute_code == "price")
            continue;
            if (empty($_REQUEST[$attribute_code])){continue;}
            if(!empty($_REQUEST[$attribute_code]) && is_array($_REQUEST[$attribute_code]))
                $collection->addAttributeToFilter($attribute_code, array('in' => $_REQUEST[$attribute_code]));
            else
            if(!empty($_REQUEST[$attribute_code]))
            $collection->addAttributeToFilter($attribute_code, array('like' => "%" . $_REQUEST[$attribute_code] . "%"));
        }
        $collection->setStore(Mage::app()->getStore())
        ->addMinimalPrice()
        ->addFinalPrice()
        ->addTaxPercents()
        ->addStoreFilter()
        ->addUrlRewrite();
        Mage::getSingleton('catalogsearch/advanced')->prepareProductCollection($collection);    
    }
    Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
    Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);
    return $this;
}

Than after change getProductCollection and getSearchCriterias function as below in app/code/core/Mage/CatalogSearch/Model/Advanced.php file.

public function getProductCollection()
{
    if (is_null($this->_productCollection)) {
        $this->_productCollection = Mage::getResourceModel('catalogsearch/advanced_collection')
        ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
        ->addMinimalPrice()
        ->addStoreFilter();
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($this->_productCollection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($this->_productCollection);
        if(isset($_GET['cat']) && is_numeric($_GET['cat']))
        $this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['cat']),true);
    }
    return $this->_productCollection;
}
public function getSearchCriterias()
{
    $search = $this->_searchCriterias;
    if(isset($_GET['cat']) && is_numeric($_GET['cat'])){
        $category = Mage::getModel('catalog/category')->load($_GET['cat']);
        $search[] = array('name'=>'Category','value'=>$category->getName());
    }
    return $search;
}

Here in below layer navigation is prepared for advance search product collection now must display that layer navigation using theme xml file so edit your theme's catalogsearch.xml file and add below code in <catalogsearch_advanced_result> tag.
 
<reference name="left">
  <block type="catalogsearch/layer" name="catalogsearch.leftnav" after="currency" template="catalog/layer/view.phtml"/>
</reference>
 
here add that navigation in left sidebar you can put in content or right side according to theme content or template.

Friday, April 22, 2016

Solve 'Numeric value out of range: 1690' Error in Magento

Magento is mostly used e-commerce platform based on PHP. So when you work on this platform as a developer or site owner than it's hard to fetch some complicated error occur in Magento admin panel or front.
In Magento admin panel when you try to delete any product, customer or order than some times it's display 'SQLSTATE [22003]: Numeric value out of range: 1690' and product or customer not deleted.This error because of table attributes not supported data value in MySql database. This error because of table attribute not supported data value in MySql database. This error because of some big value store in databases and that structure not support that value.
So here is a simple way for solving this error. In Magento all table connect to each other with foreign key relation so this error, mostly on the order table so you just change as below or order table.
  • Login to your database using PhpMyadmin in localhost or via cPanel.
  • Select Magento database (If you don't know than find in `local.xml` file in app/etc/).
  • First tack backup of complete database before change anything(using export functionality) so revert back in case of any problem.
  • Select `sales_flat_quote` table.(If your db have prefix than find table according to that)
  • Click on `Structure` tab from top.
  • Click on Change/Edit row `items_count`
  • In `Attributes` drop down change value from `UNSIGNED` to the very top value which is blank ‘(no value)’
  • Click on save for change table structure.
  • Now clear all Magento caches and try to delete it's worked.

Thursday, March 10, 2016

Magento Interview Questions and Answers


Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store. Magento intuitive administration interface features powerful marketing, search engine optimization and catalog-management tools to give merchants the power to create sites that are tailored to their unique business needs.
Here below display basic question and answer in Magento that mostly asked by Interviewer.

Question 1. Which technology does Magento use?

Zend Framework (PHP), MySQL/MySQLI, CSS, javaScript and HTML

Question 2. Mention what are the basic features of Magento?

Basic features of Magento includes
1. Reporting and Analytic
2. Product and Catalog Browsing
3. Customer Accounts
4. Order Management
5. Payment
6. Site Management
7. Shipping
8. Search engine optimization
9. Marketing promotions and tools
10.Checkout
11.International Support

Question 3. Mention what is the limitation of Magento?

1. Magento is supported by PHP, comparatively to other e-commerce solutions, Magento might be slow in performance
2. It becomes a complex system if it is not using object-oriented programming.
3. Magento requires much space and memory.
4. Magento is not recommended for small projects/website.
5. Deep customization requires a better understanding of Magento & it's database table structure etc.

Question 4. How to upgrade to the latest version using Magento connect?

Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.

Question 5. What is EAV in Magento?

Full form of EAV is Entity Attribute Value model.
EAV is a data model to data model to describe entities.
In EAV data are stored in different smaller tables rather than storing in a single table.
Example :
Product name is stored in catalog_product_entity_varchar table.
Product id is stored in catalog_product_entity_int table.
Product price is stored in catalog_product_entity_decimal table.

Question 6. Explain Magento's MVC architecture.

MVC stands for Model-View-Controller. Any application that separates it’s data access, business logic and user interface is called MVC. There can be two types of MVC: convention-based & configuration-based.
Example:
- CakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines.
- Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has Controller (for Routing), Block (for Business Logic), Model (for DB access, sql) and Template file (for Presentation i.e. View).

Question 7. How does Magento ORM works?

ORM full form is Object Relational Mapping.
ORM is a programming technique which is used to convert different types of data to Objects and vice versa. ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.
1. Simple
2. EAV Model

Question 8. Explain about the modules of Magento.

Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.
There are three categories of modules hosted on Magento Connect:
1. Core Modules
2. Community Modules
3. Commercial Modules
Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

Question 9. How many types of products Magento provide?

1. Simple Products
A Magento simple product is the most used product type for Magento web shops. This is because it’s the most general product type of them all. A Magento simple product should be used for a single item without any specific select variations. Think about a coffee cup, a chandelier, a table or whatever.

2. Grouped Products
A Magento grouped product should be used for a combination of Magento simple products. Think about a coffee cup that is sold together with a saucer, a silver spoon, a breakfast plate or whatever. You can’t define a specific price for a Magento grouped product but you can define a discount amount.

3. Configurable Products
A Magento configurable product should be used for a single item with specific select variations. Think about a coffee cup obtainable in different colors and sizes, a woman’s bag obtainable in different materials, a light boll obtainable in different watts or whatever. Each selected variation can have its own additional costs.

4. Virtual Products
A Magento virtual product should be used for a virtual (not touchable) item. Think about an insurance, a reservation, an extra product guarantee or whatever. A virtual product does not allow selecting a shipping method at checkout simply because there’s nothing to ship.

5. Bundle Products
A Magento bundle product should be used for a bundle of simple (or virtual) products which are not to be sold separately. Think about a laptop where the customer can choose various items such as hard disk, processor, internal memory or whatever. Each of these items are simple (or virtual) products but can only be sold within the bundle product.

6. Downloadable Products
A Magento downloadable product should be used for online software items. Think about an MP3 file, a PowerPoint presentation, a Magento extension or whatever. A downloadable product does not allow selecting a shipping method at checkout simply because there’s nothing to ship.

Question 10. Explain how you can change Magento Core API settings?

To change Magento Core API settings, you have to
Go to Admin menu, choose System -> Configuration
Select Magento Core API on the left side of the Configuration Panel, under Services
Tap on to expand the General Settings section and you can
Type the name of the Default Response Charset that you want to use
Determine the Client Session Timeout in seconds
Click the Save Config button when complete.

Question 11. Mention what is the benefit of applying Connect Patches in Magento?

In Magento, applying connect patch
It enables easy installation of packages with installation; it overwrites any existing translations for the same time
For enhancing security, by default Magento Connect uses HTTP to download extensions instead of FTP
With a dash character in the name, extension developers can now create extensions
Magento administrators will be informed now who tries to install an extension with insufficient file system privileges.

Question 12. How will you enable maintenance mode of your Magento website?

If you want your Magento website to show in maintenance mode, you will have to do two things.
1. Create a file name maintenance.flag in your Magento root directory. Contents under this file doesn’t matter, you can keep it empty.
2. Change the maintenance file (located in Magento root -> errors -> default directory) to show proper message when user visits your website.

Question 13. How will you enable maintenance mode of your Magento website?

Steps to create custom Magento module:
Namespace : Newsinfo
Module Name : Mymodule
1. Create directory Mymodule in app/code/local/Newsinfo
2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.
3. Create module configuration file (app/code/local/Newsinfo/Mymodule/etc/config.xml).
4. Create xml file (app/etc/modules/Newsinfo_ Mymodule.xml)to enable/disable module and tell Magento system from which code pool that module will be taken.

Question 14. How to improve Magento performance?

1. Enabled Magento caching
2. MySQL Query caching
3. Enable Gzip Compression
4. Disable any unused modules
5. Disable the Magento log
6. Optimize your images
7. Combine external CSS/JS into one file
8. Enable Apache KeepAlives: Make sure your Apache configuration has KeepAlives enabled.
9. Optimize your Server
10.Use a Content Delivery Network (CDN)

Question 15. Which factors affect performance of Magento?

1. EAV structure of Magento database, even for retrieving single entity the query becomes very complex .
2. Magento’s template system involves a lot of recursive rendering.
3. Huge XML trees built up for layout configuration, application configuration settings.

Question 16. What is Magento's compilation feature?

The Compilation feature of Magento will allow you to compile all files of a Magento installation in order to create a single include path to increase performance. The performance increase is between 25%-50% on page loads. In order to use this tool, the directory 'includes' and the file 'includes/config.php' must both be writable.
Note: Before you make any changes to your Magento installation you should always disable compilation. Once the changes are made, run the compilation process, and then enable it.

Question 17. How indexing works in Magento and why it require?

There are different kind of indexes in Magento. All of the indexers are there to make things run faster.
Flat Index
There are 2 such indexes. One for categories and one for products.
By default the category and product entities (and customers and customer addresses but they are not important in this situation) are EAV entities. This is very nice for extensibility. But it's a performance killer because in order to get all values for all the attributes you need a lot of joins or multiple queries.
Here is where the flat indexer comes into play.
It transforms the EAV structure into a flat structure. I mean it creates a table (one for each store view in Magento) that has one column corresponding to an attribute. This makes selects faster. For categories all attributes are converted to table columns. For products only the ones you mark as 'Used in product listing' because you can sell all types of products with different attributes and creating one table with a gazillion columns may not be possible.
Also, some products may be disabled or may not belong to a certain website and there is no need to include them in the entries to search. They are excluded by the indexer.
The generated flat tables are used for reading data in the fronend. The backend still uses the EAV structure.

Catalog Search Index
You can search for products by many attribute values. Some of them may not be included in the flat tables generated by the flat indexer. This index fills in a table with the searchable attribute values for products so it's easier to look for them based on keywords. Having all the info in one table (or one field) makes it possible to use Full text search and get relevant results.

Product Prices
The price of a product can be affected by many variables. For example, customer group, website, catalog discount rules.
Same as above, getting the products with their prices will mean a lot of joins or multiple selects. IN addition bundle products have a strange pricing system. This indexer aggregates the data in some tables (catalog_product_index_price_*) and makes the selects (sorting and filtering) much easier.

Catalog URL Rewrites
This cleans up the url rewrite rules by setting which url corresponds to which product or category. It's easier this way for the url management internal system to decide which page should you view when calling a non-standard url. Instead of searching through all the product and categories URL keys it just searches in one table.

Category Products
In Magento you can set a category attribute named 'Is Anchor' to true or false. If it's true it means that the category in question will list all the products from it's child categories. Again, determining this realtime it will take more resources than just reading one table. This indexer creates the association between products and categories based on the associations you set in the backend and the 'Is Anchor' flag on the categories.

Stock Status
For simple products it's easy. They can be in stock or out of stock, but for configurable, grouped and bundle is not that easy. They can be in stock or out of stock depending on the child products associated to the main product. Again (I'm just repeating my self here) getting their status real time would mean a lot of queries.

Product Attributes
This one collects all attributes that can be used in the layered navigation for same reason. Having all of them in one place for faster reading.

Tag Aggregation
I have no idea what this does. I've never used tags in a real live project.

Question 18. How to change admin URL of Magento?

There are 2 ways to change admin URL of Magento:
1: Go to app/etc/local.xml file, search for <frontName>tag, replace adminpanel with your new admin url
e.g we have changed the adminpanel URL to adminmagento in below example

<admin>
    <routers>
        <adminhtml>
            <args>
                <frontName><![CDATA[adminmagento]]></frontName>
            </args>
        </adminhtml>
    </routers>
</admin>

2: You can also change Admin URL of Magento in Admin panel of Magento
In your admin panel, go to  System -> Configuration->Advanced ->Admin->Admin Base URL->Use Custom Admin URL, select to  ‘yes’ to use custom admin URL, now enter new admin path in `Custom admin path` field and save it.

Question 19. What is the difference between Mage::getSingletone() andMage::getModel() in Magento?

Mage::getSingletone() always finds for an existing object if not then create that a new object but Mage::getModel() always creates a new object.

Question 20. How find Magento version?

Mage::getVersion(); which is stored in app/Mage.php file.

Question 21. Difference between 'controller' and 'controllers'

The difference is in the auto loading, as you have mentioned. In general files that are in /Controller are Abstract (or parent) classes from which classes in /controllers inherit.

Question 22. How to add an external javascript/css file in Magento?

Add CSS File
<action method="addCss"><stylesheet>css/yourstyle.css</stylesheet></action>
Add JS File
<action method="addJs"><script>js/yourfile.js</script></action>

Question 23. Get Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url.

1. Get Base Url :
Mage::getBaseUrl();

2. Get Skin Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
(a) Unsecure Skin Url :
$this->getSkinUrl('images/imagename.jpg');
(b) Secure Skin Url :
$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));

3. Get Media Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

4. Get Js Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);

5. Get Store Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

6. Get Current Url
Mage::helper('core/url')->getCurrentUrl();

Get Url in cms pages or static blocks
1. Get Base Url : {{store url=""}}
2. Get Skin Url : {{skin url='images/imagename.jpg'}}
3. Get Media Url : {{media url='/imagename.jpg'}}
4. Get Store Url : {{store url='mypage.html'}}

Question 24. Type of session in Magento.

customer/session, checkout/session, core/session

Question 25. How to run custom query in Magento?

$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$result=$db->query('SELECT * FROM TABLE WHERE id=1');

Question 26. How to include CMS block in template file(.phtml)?

Access block's content from .phtml template file by :
echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘static_block_id’)->toHTML();

Question 27. How to get the total price of items currently in the cart?

Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal();

Question 28. How to set different themes for logged in users?

if(Mage::getSingleton(‘customer/session’)->isLoggedIn()):
Mage::getDesign()->setPackageName(‘package_name’)->setTheme(‘themename’);
endif;

Question 29. How to fetch 5 bestsellers products pro-grammatically?

Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’)
->setPage(1, 5)
->load();

Question 30. Get all products by category in Magento.

$products = Mage::getModel('catalog/category')->load($category_id)
 ->getProductCollection()
 ->addAttributeToSelect('*') // add all attributes - optional
 ->addAttributeToFilter('status', 1) // enabled
 ->addAttributeToFilter('visibility', 4) //visibility in catalog,search

Question 31. What are the addAttributeToFilter Conditionals in Magento?

In Magento we can use addAttributeToFilter Conditions same as where in SQL.
Below are the all condtions:
Equals: eq
$_products->addAttributeToFilter('status', array('eq' => 1));
Not Equals - neq
$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));
Like - like
$_products->addAttributeToFilter('sku', array('like' => 'UX%'));

One thing to note about like is that you can include SQL wildcard characters such as the percent sign.

Not Like - nlike
$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));
In - in
$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));

When using in, the value parameter accepts an array of values.

Not In - nin
$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));
NULL - null
$_products->addAttributeToFilter('description', 'null');
Not NULL - notnull
$_products->addAttributeToFilter('description', 'notnull');
Greater Than - gt
$_products->addAttributeToFilter('id', array('gt' => 5));
Less Than - lt
$_products->addAttributeToFilter('id', array('lt' => 5));
Greater Than or Equals To- gteq
$_products->addAttributeToFilter('id', array('gteq' => 5));
Less Than or Equals To - lteq
$_products->addAttributeToFilter('id', array('lteq' => 5));

Question 32. How to get first item or last item from the collection?

$collection->getFirstItem() and $collection->getLastItem();

Question 33. How to convert default currency to others in Magento?

Mage::helper('directory')->currencyConvert($price, USD, GBP);

Question 34. What are 'magic methods' in Magento?

Magento uses __call(), __get(), __set(), __uns(), __has(), __isset(), __toString(), __construct(), etc. magic methods. You can find more details inside class Varien_Object
For more information about magic methods: http://php.net/manual/en/language.oop5.magic.php

Question 35. Explain the difference between Final class and Abstract class?

Final Class:
A Class which Can't be inherited by other class, that class is called final class.
You all knows that final class is inbuilt in java. But in C++ you have to create final class.Two types of Final class, you can create. One who want to create object of final class on Heap and other who wants to create object of Final class on stack.
1. It makes use of private constructor, virtual inheritance and friend class.
2. In place of private constructor, use private Destructor.
Because Constructor can be overloaded and Destructor can't be overloaded.

Wednesday, March 9, 2016

Add Custom Tabs to Magento Product/Customer in Admin Panel


Magento provides the best functionality for managing products from admin panel and also all basic features provide as edit the product. all fields in Magento products group by tab menu. same for customers.
For developer sometimes need to add extra features as a tab in product or customer edit functionality. that time you can create new extension for overwrite Magento functionality or directly edit core files.So here describe basic changes for how to add extra tab menu in product and customer edit screen.
If you want to add product tab in product details than navigate to `app\code\core\Mage\Adminhtml\Block\Catalog\Product\Edit\Tabs.php` file and add below code in `_prepareLayout()` function.

$this->addTab('Custom',array(
'label' =>Mage::helper('catalog')->__('Custom'),
'class' =>   'ajax',
'url'   =>   $this->getUrl('*/*/custom',array('_current'=>true)),
));

same for customer add code as below in `app\code\core\Mage\Adminhtml\Block\Customer\Edit\Tabs.php` file and add own file in 'Tab' folder on same location or create custom action in controller file.
Create new extension for that according to Magento extension structure.first create new `Newsinfo_Customtabs.xml` file in `app\etc\modules\` with below code.

<config>
    <modules>
        <newsinfo_customtabs>
            <active>true</active>
            <codepool>local</codepool>
        </newsinfo_customtabs>
    </modules>
</config>

Create `config.xml` file in `app\code\local\Newsinfo\Customtabs\etc\`with below code.

<?xml version="1.0"?>
<config>
  <modules>
    <Newsinfo_CustomTabs>
      <version>0.1.0</version>
    </Newsinfo_CustomTabs>
  </modules>
  <global>
    <blocks>
      <customtabs>
        <class>Newsinfo_Customtabs_Block</class>
      </customtabs>
    </blocks>
    <models>
      <customtabs>
        <class>Newsinfo_Customtabs_Model</class>
      </customtabs>
    </models>
  </global>
  <adminhtml>
    <layout>
      <updates>
        <customtabs>
          <file>customtabs.xml</file>
        </customtabs>
      </updates>
    </layout>
    <events>
      <catalog_product_save_after> //for customer customer_save_after
        <observers>
          <newsinfo_save_product_data> //for customer newsinfo_save_customer_data 
            <type>singleton</type>
            <class>customtabs/observer</class>
            <method>saveProductTabData</method>
          </newsinfo_save_product_data>
        </observers>
      </catalog_product_save_after>
    </events>
  </adminhtml>
</config>

Here below display observer event after save product/customer data.create new `Tab.php` file in `app\code\local\Newsinfo\Customtabs\Block\Adminhtml\Catalog\Product\`(for customer file location `app\code\local\Newsinfo\Customtabs\Block\Adminhtml\Customer\`) as below code.

<?php
class Newsinfo_Customtabs_Block_Adminhtml_Catalog_Product_Tab 
extends Mage_Adminhtml_Block_Template
implements Mage_Adminhtml_Block_Widget_Tab_Interface {
    public function _construct()
    {
 parent::_construct();
 $this->setTemplate('customtabs/tab.phtml');
    }
    public function getTabLabel()
    {
     return $this->__('My Custom Tab');
    }
    public function getTabTitle()
    {
     return $this->__('Click here to view your custom tab content');
    }
    public function canShowTab()
    {
  return true;
    }
    public function isHidden()
    {
     return false;
    }
}?>

Add new `customtabs.xml` file in `app\design\adminhtml\default\default\layout\`.

<?xml version="1.0"?>
<layout>
  <adminhtml_catalog_product_edit>//for customer adminhtml_customer_edit
    <reference name="product_tabs">
      <action method="addTab">
        <name>my_custom_tab</name>
        <block>customtabs/adminhtml_catalog_product_tab</block>
        //for customer adminhtml_customer_tab</action>
    </reference>
  </adminhtml_catalog_product_edit>
</layout>

Create new phtml file in admin panel that you want to display in custom tab.here just display text-box.create `tab.phtml` file in `app\design\adminhtml\default\default\template\customtabs\` as below.

<div>
  <label>Custom Field</label>
  <input name="custom_field" />
</div>

Follow below code and create new extension that displays custom tab in product/category edit section if not display than clear all cache and check again.now create `Observer.php` for save data in `app\code\local\Newsinfo\Customtabs\Model\`as below.

<?php
class Newsinfo_Customtabs_Model_Observer
{
 static protected $_singletonFlag = false;
 public function saveProductTabData(Varien_Event_Observer $observer)
 {
  if (!self::$_singletonFlag) {
   self::$_singletonFlag = true;
   $product = $observer->getEvent()->getProduct(); //For Product
   $customet = $observer->getEvent()->getCustomer(); //For Customer
   try {
    $customFieldValue =  Mage::app()->getRequest()->getPost('custom_field');
   }
   catch (Exception $e) {
    Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
   }
  }
 }
 public function getProduct() //For Product
 {
  return Mage::registry('product');
 }
 public function getCustomer() //For Customer
 {
  return Mage::registry('current_customer');
 }
}
?>