Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Thursday, July 13, 2017

Magento : add breadcrumbs to cms pages


Magento is an eCommerce application and it supports CMS features with few limitations. Magento displays, bread crumbs, which helps the user to know where they are and it displays the navigation path. Usually, the breadcrumb will be located below the header. But in Magento breadcrumb is available only in the catalog pages an not in the CMS pages or in the checkout pages.

Magento 2.X

  • On the Admin panel, Select Settings -> Stores -> Configuration.
  • In the panel on the left under General, select Web
  • Open the Default Pages section.
  • Change Show Breadcrumbs for CMS Pages to 'Yes'
  • When complete, click Save Config

Magento 1.X

`breadcrump.phtml` in `app/design/default/THEME/page` folder is responsible for displaying the breadcrumb. Add the following code to the breadcrumb.phtml file before the normal breadcrumb check to display the breadcrumb in the CMS, shopping cart and checkout pages.

if ((!$crumbs || !is_array($crumbs)) && $this->getUrl('') != $this->getUrl('*/*/*', array('_current'=>true, '_use_rewrite'=>true))) {
	$breadcrumb = $this->getLayout()->getBlock('breadcrumbs');
	$breadcrumb->addCrumb('home', array('label' => Mage::helper('cms')->__('Home'), 'title' => Mage::helper('cms')->__('Home Page'), 'link' => Mage::getBaseUrl()));
	$breadcrumb->addCrumb('my_account activetrail', array('label' => $this->getLayout()->getBlock('head')->getTitle(), 'title' => $this->getLayout()->getBlock('head')->getTitle(), 'last' => 1));
	$crumbs = $breadcrumb->_crumbs;
}
 
The above code restricts the breadcrumb to be displayed from the home page, if you want that to be shown also in the home page, then remove the following condition from the first line of the above code.

$this->getUrl('') != $this->getUrl('*/*/*', array('_current'=>true, '_use_rewrite'=>true))

Sunday, July 9, 2017

Login With Username/ Mobile in Magento 1.x






Magento provides login functionality for login to account with email and password but sometimes you want to login with customer username/mobileno with account password than here below describe how you implement this functionality in Magento 1. x modify some changes.

Here first add new customer attribute as mobile/username according to your requirement by create sql file in any extension or run installer command as below.

$installer = $this;
$installer->startSetup();
$setup = Mage::getModel('customer/entity_setup', 'core_setup');
$setup->addAttribute('customer', 'mobile', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Mobile No',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'user_defined' => 1,
    'default' => '0',
    'visible_on_front' => 1,
));
$installer->endSetup();

After execute below code in your mysql file or directly from any Magento page.Mobile No field display on website admin panel see add or edit any customer there is display mobile No field. Now you must set login with mobile no in magento front for that changes in `loginPostAction` function located in 'app/code/core/Mage/Customer/controllers/AccountController.php' as below.

public function loginPostAction()
{
    $loginpost = $this->getRequest()->getPost();
    $mobileno = $loginpost['login']['username'];
    if (filter_var($mobileno, FILTER_VALIDATE_EMAIL) //check username as email or mobile.
    {
     parent::loginPostAction(); //excute current code
    }
    else
    {
     $session = Mage::getSingleton('customer/session');
        $collection = Mage::getModel('customer/customer')->getCollection();
        $website_id = Mage::app()->getWebsite()->getId();
        $collection->addAttributeToFilter('mobile', array('eq' =>$mobileno));
        $custData = $collection->getData();
        $email = trim($custData[0]['email']);
        $customerId = (int) trim($custData[0]['entity_id']);
        try{
         $authenticateuser = Mage::getModel('customer/customer')->setWebsiteId($website_id)->authenticate($email, $username['login']['password']);
       }catch( Exception $e ){
            $session->addError('Invalid Login Detail');
            $this->_redirect('customer/account');
       }      
       try{
         if($authenticateuser && $customerId){
             $customer = Mage::getModel('customer/customer')->load($customerId);
                $session->setCustomerAsLoggedIn($customer);
                $message = $this->__('You are now logged in as %s', $customer->getName());
                $session->addSuccess($message);
            }
            else{
             throw new Exception ($this->__('The login attempt was unsuccessful. Some parameter is missing Or wrong data '));
            }
      }
      catch (Exception $e){$session->addError($e->getMessage());}
      $this->_redirect('customer/account');
    }
} 
 
Before make changes in below file you must remove email validation from your theme login. phtml file because default Magento provides only login with email so you must remove login textbox validation by removing validate-email` class of the textbox.
Here customer login using mobileno/username. You can set customer attribute as unique for preventing duplication. You can also check below logic before saving any customer as below.

$customer = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('mobileno')->addAttributeToFilter('mobileno',{Val})->load();
if (is_object($customer)){
 //Customer already exits with same mobileno
}

Magento 2 : List of all console command (CLI)

Magento 2 is new version of Magento with new structure, design and some functionality improve and include for creating a fully customized store. for any developer who works on Magento 2 than much familiar with Magento command line arguments. For use Magento CLI in any operating system need some system requirements for Magento check all configuration Here.
Magento has one command-line interface that performs both installation and configuration tasks. So you can install Magento using command line. Here below table summarizes the available commands in Magento 2. from that some are most used when you develop websites in Magento 2.
Every command run in bin directory of your Magento installation. so first navigate to that directory than use below commands.
When you run want to run command from Magento root directory than write command as `php bin/magento COMMAND`. You can also create own command to run in CLI.

Command Use
admin
magento admin:user:create [--<parameter_name>=<value>, ...] Create a new administrator or to edit an existing administrator
magento admin:user:unlock [admin_user_name] Unlock the account of an administrator that was locked
app
magento app:config:dump Create dump of application
cache
magento cache:status To view the status of the cache
magento cache:enable [type] Omitting [type] enables or disables all cache types at the same time
magento cache:disable [type] This command disable all([type]) types
mmagento cache:clean [type] Deletes all items from enabled Magento cache types only
mmagento cache:flush [type] Flushing a cache type purges the cache storage
cron
magento cron:run [--group="<cron group name>"] To set up(run) custom cron jobs and groups
customer
magento customer:hash:upgrade Upgrade customer hash according to latest algorithm.It helps to increase customer Password security
deploy
magento deploy:mode:show Displays current application mode
magento deploy:mode:set {mode} Change application mode either developer or production
dev
magento dev:source-theme:display Collects and publishes source files for theme
magento dev:tests:run Runs test(all, unit, integration, integration-all, static, static-all, integrity, legacy, default)
magento dev:urn-catalog:generate <path> Generates the catalog of URNs to *.xsd for IDE to highlight XML(Currently, only PHPStorm is supported)
magento dev:xml:convert [-o|--overwrite] {xml file} {xslt stylesheet} Update your layout XML files if you update the corresponding Extensible Style sheet Language Transformations (XSLT) style sheet.
i18n
magento i18n:collect-phrases [-o|--output="<csv file path and name>"] [-m|--magento] <path to directory to translate> Run the translation collection command to extract translatable words and phrases from enabled components
magento i18n:pack [-m|--mode={merge|replace}] [-d|--allow-duplicates] <ource> <locale> Save language package
magento i18n:uninstall [-b|--backup-code] {language package name} ... {language package name} Uninstall language package
indexer
magento indexer:info View the list of indexers
magento indexer:status [indexer] View the status of all or selected indexers
magento indexer:reindex [indexer] Re-index all or selected indexers one time only
magento indexer:show-mode [indexer] To view the current/all indexer configuration
magento indexer:set-mode {realtime|schedule} [indexer] To specify the indexer configuration
magento indexer:reset [indexer] To reset current/all indexer
info
magento info:adminuri Displays Magento admin URI
magento info:backups:list Prints all lists of backup files
magento info:currency:list Displays list of available currencies
magento info:dependencies:show-modules [-d|--directory=" "] [-o|--output="<path and filename>" Show number of dependencies between module
magento info:dependencies:show-modules-circular [-d|--directory=" "] [-o|--output="<path and filename>" Show number of circular dependencies between module
magento info:dependencies:show-framework [-d|--directory=" "] [-o|--output="<path and filename>" Show number of dependencies on Magento framework
magento info:language:list Displays list of available languages
magento info:timezone:list Displays list of available time zones
maintenance
magento maintenance:allow-ips <ip address> .. <ip address> [--none] Maintain the list of exempt IP addresses
magento maintenance:enable [--ip=<ip address> ... --ip=<ip address>] | [ip=none] Enable maintenance mode
magento maintenance:disable [--ip=<ip address> ... --ip=<ip address>] | [ip=none] Disable maintenance mode
magento maintenance:status Displays maintenance mode status
module
magento module:enable [-c|--clear-static-content] [-f|--force] [--all] <module-list> Enable specified/all available modules
magento module:disable [-c|--clear-static-content] [-f|--force] [--all] <module-list> Disable specified/all available modules
magento module:status Displays status of all available modules
magento module:uninstall [--backup-code] [--backup-media] [--backup-db] [-r|--remove-data] [-c|--clear-static-content] \ {ModuleName} ... {ModuleName} Uninstall module\modules {ModuleName} define as <VendorName>_<ModuleName>
sample data
magento sampledata:deploy Deploy sample data module
magento sampledata:remove Remove all sample data packages from composer.json
magento sampledata:reset Reset all sample data modules for re-installation
setup
magento setup:backup [--code] [--media] [--db] Takes backup of Magento application code base, media and database
magento setup:config:set [--<parameter>=<value>, ...] To update the deployment configuration without affecting anything else
magento cron:run [--group="<cron group name>"] Runs all/specifies cron job schedule for setup application
magento setup:db-schema:upgrade Install and upgrade schema in DB
magento setup:db-data:upgrade Install and upgrade data in DB
magento setup:db:status Check if DB data or schema requires upgrade
magento setup:install --<option>=<value> ... --<option><value> Install the Magento application database schema and data with configuration
magento setup:upgrade [--keep-generated] Upgrade the Magento application database schema and data
magento setup:uninstall Uninstalling the Magento software drops and restores the database, removes the deployment configuration, and clears directories
magento setup:di:compile Compile code to generated code and dependency injection configuration
magento setup:rollback [-c|--code-file="<name>"] [-m|--media-file="<name>"] [-d|--db-file="<name>"] Rollback of Magento application code base, media and database according to backup
magento setup:perf:generate-fixtures {path to profile} Generate data for performance testing
magento setup:store-config:set [--<parameter_name>=<value>, ...] Install & configure the store with basic parameters
magento setup:static-content:deploy [<list of languages>] [-t|--theme[="<theme>"]] [--exclude-theme[="<theme>"]] [-l|--language[="<language>"]] [--exclude-language[="<language>"]] [-a|--area[="<area>"]] [--exclude-area[="<area>"]] [-j|--jobs[=">number>"]] [--no-javascript] [--no-css] [--no-less] [--no-images] [--no-fonts] [--no-html] [--no-misc] [--no-html-minify] [-d|--dry-run] Run the static view files deployment
theme
magento theme:uninstall [--backup-code] [-c|--clear-static-content] {theme path} Uninstall themes Composer packages

Wednesday, November 30, 2016

Install Magento 2 on Localhost With PHP7

New version of Magento changed with a new structure and design that improves features which are convenient. You can also check all changes and features on the Magento official website and you can also download latest version from there.
If you are using Magento 2.0.X than its support in PHP 5 but when you use latest Magento 2.1.x than it's supported in PHP 7 & MySQL 5.7 and it's also support Elasticsearch 1.0. Here I describe you to install Magento 2 using EasyPHP DevServer v16. 1 including Apache 2.4.17, PHPv7.0.1, MySQL v5.7.9 and PhpMyAdmin v4.5.2.
For installing Magento using an EasyPhp server without installing Wamp or xamp you must download EasyPhp for your system and install it.
Than download composer and install in system with `php.exe` path from EasyPhp installation.
Here below describe the steps for run Magento 2 on the local server.

  • Start EasyPHP DevServer by clicking on EasyPHP DevServer -> Open Dashboard (If it's display msvcr100.dll error than download "Microsoft Visual Studio C++ 2015 & 2013" according to EasyPhp installation folder(84x or 64x) not window system)
  • Click on HTTP Server -> Apache -> PHP v7.0.1 and Port 8888 -> start
  • Click on DB Server -> MySQL -> start.
  • Back to Dashboard again and click on the Portable Direction link to detect the directory, then extract Magento 2 files which we just download before. This is ‘ROOT’ Directory of your local hosting.
  • Extract all files from the Magento 2 zip file to directory.
  • Create new database from Dashboard -> PhpMyAdmin.
  • Before install Magento first check your `php.ini` file in EasyPHP_FOLDER/eds-binaries/php/PHP_VERSION and remove ";" for active below extensions.
    • mcrypt
    • mhash
    • mbstring
    • Curl
    • simpleXML
    • gd
    • xsl
    • soap
    • openssl
    For example change ";extension=php_curl.dll" to "extension=php_curl.dll"
  •  Now open magento 2 directory folder in your browser "http://127.0.0.1:8888/MAGENTO2/"(server Url according to you set in EasyPHP dashboard)
  • Start Magento Installation and check 'Readiness'. If you got any error then check `php. ini` file PHP version and restart the Apache serve.
    • If you got Curl starting Error than copy `libssh2.dll` from php directory to `Window/system` directory
    • Copy all `icu*.dll` files from eds-binaries/php/PHP_VERSION` to `eds-binaries/httpserver/APACHEVERSION`
    • If you got any other extension error than copy related dll file from `eds-binaries/php/PHP_VERSION` to `eds-binaries/httpserver/APACHEVERSION`
  • Than set database details and store configuration and complete installation process.
  • Now open command prompt using window+R or search `cmd`.
  • Enter Magento installation directory in CMD and run below code `composer install`
  • Perform installing static content to deploy on you Magento shop by typing `php bin/magento setup:static-content:deploy` (Or you can use `php -dmemory_limit=6G bin/magento setup:static-content:deploy`)
  • Clean Magento 2 cache by typing ‘php bin/magento cache:flush’ in the CMD
  • Re-index Magento Static Blocks by typing `php bin/magento indexer:reindex`.

Now your magento 2 working complete on your installation URL http://127.0.0.1:8888/MAGENTO2/
If you got any error or fetch any problem during installation than you can re-install it using below process.

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

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;

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

Tuesday, March 8, 2016

Display Category Collection With Toolbar in Magento

Magento provide product listing with Grid view and List view,Order by ascending and descending with pagination functionality which is best and highly designed website functionality but some times you want to implement that toolbar functionality for category collection. For some Magento story design you want to implement sub category listing same as products listing than you must modify Magento core functionality because it not provide this type of functionality.
See below process for create own extension in local pool for display sub category listing with toolbar.
Create new `Newsinfo_Subcategories.xml` file in `app\etc\modules\` as below code.

<?xml version="1.0"?>
<config>
    <modules>
        <Newsinfo_Subcategories>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Catalog />
            </depends>
        </Newsinfo_Subcategories>
    </modules>
</config>
 
Create new `config.xml` file in `app\code\local\Newsinfo\Subcategories\etc\`as below code.

<?xml version="1.0"?>
<config>
    <modules>
        <Newsinfo_Subcategories>
            <version>1.0.0</version>
        </Newsinfo_Subcategories>
    </modules>
    <global>
        <blocks>
            <grbrains>
                <class>Newsinfo_Subcategories_Block</class>
            </grbrains>
        </blocks>
        <helpers>
            <grbrains>
                <class>Newsinfo_Subcategories_Helper</class>
            </grbrains>
        </helpers>
    </global>
</config> 

create new `Data.php` file in`app\code\local\Newsinfo\Subcategories\Helper\` with class as below.


class Newsinfo_Subcategories_Helper_Data extends Mage_Core_Helper_Abstract
{
   //Enter helper data functions.
 }
create new `Subcategories.php` file in `app\code\local\Newsinfo\Subcategories\Block\`that display subcategories on fronted as below code.

class Newsinfo_Subcategories_Block_Subcategories extends Mage_Core_Block_Template
{
    public function __construct()
    {
        parent::__construct();
        $category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
        $collection = Mage::getModel('catalog/category')->getCollection();
        $collection->addFieldToFilter('parent_id',$category->getId());
        $collection->addIsActiveFilter();
        $collection->addNameToResult();
        $collection->addUrlRewriteToResult();
        $this->setCollection($collection);
    }
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        $parent_id = Mage::app()->getStore()->getRootCategoryId();
        if($this->getRequest()->getParam('category_id',false)){
            $parent_id = $this->getRequest()->getParam('category_id');
        }
        $category = Mage::getModel('catalog/category')->load($parent_id);
 
        if ($headBlock = $this->getLayout()->getBlock('head')) {
            if ($title = $category->getMetaTitle()) {
                $headBlock->setTitle($title);
            }
            if ($description = $category->getMetaDescription()) {
                $headBlock->setDescription($description);
            }
            if ($keywords = $category->getMetaKeywords()) {
                $headBlock->setKeywords($keywords);
            }
        } 
        $toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
  $pager = $this->getLayout()->createBlock('page/html_pager', microtime());
        $toolbar->setChild('product_list_toolbar_pager', $pager);
        $collection = $this->getCollection();
        if ($orders = $this->getAvailableOrders()) {
            $toolbar->setAvailableOrders($orders);
        }
        if ($sort = $this->getSortBy()) {
            $toolbar->setDefaultOrder($sort);
        }
        if ($dir = $this->getDefaultDirection()) {
            $toolbar->setDefaultDirection($dir);
        }
        $toolbar->setCollection($collection);
 
        $this->setChild('toolbar', $toolbar);
  
        $this->getCollection()->load();
        return $this;
    }
    public function getDefaultDirection(){
        return 'asc';
    }
    public function getAvailableOrders(){
        return array('name'=> 'Name','position'=>'Position','children_count'=>'Sub Category Count');
    }
    public function getSortBy(){
        return 'position';
    }
    public function getMode()
    {
       return $this->getChild('toolbar')->getCurrentMode();
    }
    public function getToolbarHtml()
    {
        return $this->getChildHtml('toolbar');
    }
 public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
}

Now it's ready for call in website here display all sub category listing than first create new static block from Admin->CMS->Static Blocks->Add New Block with below details.

Block Title : Sub Categories
Identifier : subcategories
Status : Enable
Content :{{block type="newsinfo/subcategories" template="catalog/category/subcategory.phtml"}}

Save below block and  set block permission from Admin->System->Permission->Blocks and create new block with name as`newsinfo/subcategories` and status as `Allowed`.
Now call created static block on any category from Admin->catalog->Manage Categories->CATEGORY->Display Settings set `Display Mode` as `Static block only` and `CMS Block` as  'Sub Categories' (created as below).
Now create `subcategory.phtml` file in `app\design\frontend\THEME\default\template\catalog\category\` as below code.

<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
<?php $collection = $this->getCollection(); ?>
<?php echo $this->getToolbarHtml(); ?>
<?php if($collection->getSize()): ?>
  <?php if($this->getMode()!='grid'): ?>
  <!-- List Model -->
  <?php $_iterator = 0; ?>
  <ol class="products-list" id="products-list">
    <?php foreach ($collection as $category):
        $category = Mage::getModel('catalog/category')->load($category->getId()); ?>
    <li class="item<?php if( ++$_iterator == sizeof($collection) ): ?> last<?php endif; ?>"> <a href="<?php echo $category->getUrl() ?>" title="<?php echo $this->stripTags($category->getName()); ?>" class="product-image"><img src="<?php echo $category->getImageUrl();?>" alt="<?php echo $this->stripTags($category->getName()) ?>" /></a>
      <div class="product-shop">
        <div class="f-fix">
          <?php $_productNameStripped = $this->stripTags($category->getName(), null, true); ?>
          <h2 class="product-name"><a href="<?php echo $category->getUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $category->getName(); ?></a></h2>
          <div class="desc std"> <?php echo $category->getDescription(); ?></div>
        </div>
      </div>
    </li>
    <?php endforeach; ?>
  </ol>
  <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
  <?php else: ?>
  <!-- Grid Mode -->
  <?php $_collectionSize = $collection->count() ?>
  <?php $_columnCount = $this->getColumnCount();if(!$_columnCount){$_columnCount = 3;}?>
  <?php $i=0; foreach ($collection as $category):
    $category = Mage::getModel('catalog/category')->load($category->getId());?>
  <?php if ($i++%$_columnCount==0): ?>
  <ul>
    <?php endif;?>
    <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
      <div class="product-bdr-area">
        <div class="product-img-area"> <a href="<?php echo $category->getUrl() ?>" title="<?php echo $this->stripTags($category->getName()); ?>" class="product-image"><img src="<?php echo $category->getImageUrl()?>" alt="<?php echo $this->stripTags($category->getName()) ?>" /></a> <a href="<?php echo $category->getUrl() ?>" title="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?></a> </div>
      </div>
    </li>
    <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
  </ul>
  <?php endif ?>
  <?php endforeach ?>
  <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
  <?php endif; ?>
<?php else: ?>
<p class="note-msg"><?php echo $this->__('There is no sub category'); ?></p>
<?php endif ?>

Saturday, February 20, 2016

Get Full Product URL Including Category in Magento


Magento is e-commerce open source for based on PHP for creating shopping based website all over the world. If you are Magento developer or need some customization in Magento that must need Magento product page URL for display product anywhere in the website.
For getting product URL in Magento use `getProductUrl()`  function. when you visit product from category listing that it's display full URL with category and when use getProductUrl() function that it's display only product URL and also change breadcrumbs.so that time you must need full product URL.so just create new function in product model.
open file `app/code/local/Mage/Catalog/Model/Product.php` and add below function in `Mage_Catalog_Model_Product` class.


public function getFullProductUrl( $product ){
 if(is_object($product) && $product->getSku()){
 $proArr = $product->getCategoryIds();
 // first try SQL approach
 try{
  $query      = "SELECT `request_path` FROM `".Mage::getConfig()->getTablePrefix()."core_url_rewrite` WHERE `product_id`='" . $product->getEntityId() . "'".((end($proArr)) ? 'AND `category_id`='.end($proArr) : '')." AND `store_id`='" . Mage::app()->getStore()->getId() . "';";
  $read       = Mage::getSingleton('core/resource')->getConnection('core_read');
  $result     = $read->fetchRow($query);
  return Mage::getUrl('').$result['request_path'];
 }
 catch(Exception $e){
  $allCategoryIds     = $product->getCategoryIds();
  $lastCategoryId     = end($allCategoryIds);
  $lastCategory       = Mage::getModel('catalog/category')->load($lastCategoryId);
  $lastCategoryUrl    = $lastCategory->getUrl();
  $fullProductUrl     = str_replace(Mage::getStoreConfig('catalog/seo/category_url_suffix'), '/', $lastCategoryUrl) . basename( $product->getUrlKey() ) . Mage::getStoreConfig('catalog/seo/product_url_suffix');
  return $fullProductUrl;
 }
  }
  return false;
}

Now call below function in theme files by call product model use below code for get full product URL.

 
$getproduct =Mage::getModel('catalog/product')->load($productid); //use $_products->getId();
$getproduct ->getFullProductUrl($getproduct ); 


Here you can also create own extension by extend `Mage_Catalog_Model_Product` class and add below function in that class if you want to not change magento core files.