Saturday, November 28, 2015

Add new product programmatically in Magento


In Magento development sometimes you need to add product from front end or outside of Magento folder than must add new product as programmatically. Magento provides added product features from admin panel so you can add different types of products from admin panel according to requirement. In Magento there are six types of products
  • Simple Products
  • Grouped Products
  • Configurable Products
  • Virtual Products
  • Bundled Products
  • Downloadable Products
Here below display code for adding product as programmatically according to different product types. For that you much create any PHP file in the Magento root directory by adding `app/Mage. php` file. If you want to add below code in Mageto theme files, then no need to add `Mage.php` file.

SIMPLE PRODUCT / VIRTUAL PRODUCT


require_once "app/Mage.php";
if (!Mage::isInstalled())
{
  echo "Application is not installed yet, please complete install wizard first.";exit;
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleproduct = Mage::getModel('catalog/product');
$simpleproduct->setName('PRODUCT NAME');
$simpleproduct->setSku('PRODUCT SKU');
$simpleproduct->setShortDescription('SHORT DESCRIPTION');
$simpleproduct->setDescription('PRODUCT FULL DESCRIPTION');
$simpleproduct->setTypeId('simple'); //set product type
$simpleproduct->setWeight(0); //set product weight
$simpleproduct->setNewsFromDate('08-20-2014'); //product set as new from
$simpleproduct->setNewsToDate('09-20-2014'); //product set as new to
$simpleproduct->setPrice(10.01); //set product price
$simpleproduct->setSpecialPrice(00.44); //set product special price
$simpleproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$simpleproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$simpleproduct->setMsrpEnabled(1); //apply MAP
$simpleproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$simpleproduct->setMsrp(12.0); //manufacturer's suggested retail price
$simpleproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$simpleproduct->setCreatedAt(strtotime('now'));
$simpleproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$simpleproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$simpleproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$simpleproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$simpleproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'qty' => trim(10), //quantity
   'min_qty' => 0, 
   'use_config_min_qty'=>1,
   'min_sale_qty' => 0, //minimum quantity allowed in shopping cart
   'use_config_min_sale_qty'=>1,
   'max_sale_qty' => 9999, //maximum quantity allowed in shopping cart
   'use_config_max_sale_qty'=>1,
   'is_qty_decimal' => 0,
   'backorders' => 0,
   'notify_stock_qty' => 1,
   'is_in_stock' => 1 //stock availability
 );
$simpleproduct->setData('stock_data',$stock_data);
$simpleproduct->setCategoryIds(array(2,3)); //assign categories to product
$simpleproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$simpleproduct->setMetaTitle('PRODUCT META TITLE');
$simpleproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$simpleproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$simpleproduct->save();


GROUPED PRODUCT


$groupedproduct = Mage::getModel('catalog/product');
$groupedproduct->setName('PRODUCT NAME');
$groupedproduct->setSku('PRODUCT SKU');
$groupedproduct->setShortDescription('SHORT DESCRIPTION');
$groupedproduct->setDescription('PRODUCT FULL DESCRIPTION');
$groupedproduct->setTypeId('grouped'); //set product type
$groupedproduct->setWeight(0); //set product weight
$groupedproduct->setNewsFromDate('08-20-2014'); //product set as new from
$groupedproduct->setNewsToDate('09-20-2014'); //product set as new to
$groupedproduct->setCreatedAt(strtotime('now'));
$groupedproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$groupedproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$groupedproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$groupedproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$groupedproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'is_in_stock' => 1 //stock availability
 );
$groupedproduct->setData('stock_data',$stock_data);
$groupedproduct->setCategoryIds(array(2,3)); //assign categories to product
$groupedproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$groupedproduct->setMetaTitle('PRODUCT META TITLE');
$groupedproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$groupedproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$groupedproduct->save();
$group_productid = $groupedproduct->getId(); //new saved grouped product id
Mage::getModel('catalog/product_link_api')->assign ("grouped",$group_productid,array(1,2)); //assign products as group


BUNDLE PRODUCT


$bundleproduct = Mage::getModel('catalog/product');
$bundleproduct->setName('PRODUCT NAME');
$bundleproduct->setSkuType(0); //product SKU type (0 - dynamic,1 - fixed)
$bundleproduct->setSku('PRODUCT SKU');
$bundleproduct->setShortDescription('SHORT DESCRIPTION');
$bundleproduct->setDescription('PRODUCT FULL DESCRIPTION');
$bundleproduct->setTypeId('bundle'); //set product type
$bundleproduct->setWeightType(0); //product weight type (0 - dynamic, 1 - fixed)
$bundleproduct->setWeight(0); //set product weight
$bundleproduct->setNewsFromDate('08-20-2014'); //product set as new from
$bundleproduct->setNewsToDate('09-20-2014'); //product set as new to
$bundleproduct->setPriceType(0); //price type (0 - dynamic,1 - fixed)
$bundleproduct->setPriceView(0); //price view (0 - price range,1 - as low as)
$bundleproduct->setSpecialPrice(1.0); //special price
$bundleproduct->setSpecialFromDate('08-20-2015'); //special price from (MM-DD-YYYY)
$bundleproduct->setSpecialToDate('09-20-2015'); //special price to (MM-DD-YYYY)
$bundleproduct->setCreatedAt(strtotime('now'));
$bundleproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$bundleproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$bundleproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$bundleproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'manage_stock' => 1, //manage stock
   'is_in_stock' => 1 //stock availability
 );
$bundleproduct->setData('stock_data',$stock_data);
$bundleproduct->setCategoryIds(array(2,3)); //assign categories to product
$bundleproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$bundleproduct->setShipmentType(0); //shipment type (0 - together, 1 - separately)
$bundleproduct->setMetaTitle('PRODUCT META TITLE');
$bundleproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$bundleproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$bundleoptions = array(
 '0' => array( //option array key (0,1,2,etc..)
  'title' => 'Option 0', //option title
  'option_id' => '',
  'delete' => '',
  'type' => 'select', //option type select,radio,checkbox,multi
  'required' => '1', //option is required or not (0 - not required,1- required)
  'position' => '1' //set option position
 )
);
$bundleselections = array(
        '0' => array( //option array key according to $bundleoptions
            '0' => array( //product list array key (0,1,2,etc..)
                'product_id' => '1', //product id
                'delete' => '',
                'selection_price_value' => '10', //selected option price
                'selection_price_type' => 0,
                'selection_qty' => 1, //selected product quantity
                'selection_can_change_qty' => 0, //user can chnage quantity (0 - NO,1 - YES)
                'position' => 0,
                'is_default' => 1 //set default selected option
            )
  )
 );
Mage::register('product', $bundleproduct);
Mage::register('bundleproduct', $bundleproduct);
$bundleproduct->setCanSaveConfigurableAttributes(false);
$bundleproduct->setCanSaveCustomOptions(true);
$bundleproduct->setBundleOptionsData($bundleoptions);
$bundleproduct->setBundleSelectionsData($bundleselections);
$bundleproduct->setCanSaveBundleSelections(true);
$bundleproduct->setAffectBundleProductSelections(true);
$bundleproduct->save();


CONFIGURABLE PRODUCT


$configurableproduct = Mage::getModel('catalog/product');
$configurableproduct->setName('PRODUCT NAME');
$configurableproduct->setSku('PRODUCT SKU');
$configurableproduct->setShortDescription('SHORT DESCRIPTION');
$configurableproduct->setDescription('PRODUCT FULL DESCRIPTION');
$configurableproduct->setAttributeSetId(13); // set same attribute id which is use for configure product
$configurableproduct->setWebsiteIds(array(1));
$configurableproduct->setTypeId('configurable'); //set product type
$configurableproduct->setWeight(0); //set product weight
$configurableproduct->setNewsFromDate('08-20-2014'); //product set as new from
$configurableproduct->setNewsToDate('09-20-2014'); //product set as new to
$configurableproduct->setPrice(10.01); //set product price
$configurableproduct->setSpecialPrice(00.10); //set product special price
$configurableproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$configurableproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$configurableproduct->setMsrpEnabled(1); //apply MAP
$configurableproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$configurableproduct->setMsrp(12.0); //manufacturer's suggested retail price
$configurableproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$configurableproduct->setCreatedAt(strtotime('now'));
$configurableproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$configurableproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$configurableproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$configurableproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'is_in_stock' => 1 //stock availability
 );
$configurableproduct->setData('stock_data',$stock_data);
$configurableproduct->setCategoryIds(array(2,3)); //assign categories to product
//$configurableproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$configurableproduct->setMetaTitle('PRODUCT META TITLE');
$configurableproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$configurableproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$configurableproduct->getTypeInstance()->setUsedProductAttributeIds(array(92)); //set attribute id here 92 attribute id for 'color'
$configurableProductsData = array();
$configurableAttributesData = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray();
 
$simpleProductsData = array(
    'label'         => 'Black', //attribute option label
    'attribute_id'  => 92, //set attribute id here 92 attribute id for 'color'
    'value_index'   => 10, //set value of selected color here 10 is value of 'Black' color
    'is_percent'    => 0, //set option price (0 - fixed,1 - percentage)
    'pricing_value' => 100, //selected option price
);
 
$configurableProductsData[10] = $simpleProductsData; // here 10 is configure product id which is match below attribute set and value. 
$configurableAttributesData[0]['values'][] = $simpleProductsData;
$configurableproduct->setConfigurableProductsData($configurableProductsData);
$configurableproduct->setConfigurableAttributesData($configurableAttributesData);
$configurableproduct->setCanSaveConfigurableAttributes(true);
$configurableproduct->save();


DOWNLOADABLE PRODUCT


$downloadableproduct = Mage::getModel('catalog/product');
$downloadableproduct->setName('PRODUCT NAME');
$downloadableproduct->setSku('PRODUCT SKU');
$downloadableproduct->setShortDescription('SHORT DESCRIPTION');
$downloadableproduct->setDescription('PRODUCT FULL DESCRIPTION');
$downloadableproduct->setTypeId('downloadable'); //set product type
$downloadableproduct->setWeight(0); //set product weight
$downloadableproduct->setNewsFromDate('08-20-2014'); //product set as new from
$downloadableproduct->setNewsToDate('09-20-2014'); //product set as new to
$downloadableproduct->setPrice(10.01); //set product price
$downloadableproduct->setSpecialPrice(00.44); //set product special price
$downloadableproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$downloadableproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$downloadableproduct->setMsrpEnabled(1); //apply MAP
$downloadableproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$downloadableproduct->setMsrp(12.0); //manufacturer's suggested retail price
$downloadableproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$downloadableproduct->setCreatedAt(strtotime('now'));
$downloadableproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$downloadableproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$downloadableproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$downloadableproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$downloadableproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'qty' => trim(10), //quantity
   'min_qty' => 0, 
   'use_config_min_qty'=>1,
   'min_sale_qty' => 0, //minimum quantity allowed in shopping cart
   'use_config_min_sale_qty'=>1,
   'max_sale_qty' => 9999, //maximum quantity allowed in shopping cart
   'use_config_max_sale_qty'=>1,
   'is_qty_decimal' => 0,
   'backorders' => 0,
   'notify_stock_qty' => 1,
   'is_in_stock' => 1 //stock availability
 );
$downloadableproduct->setData('stock_data',$stock_data);
$downloadableproduct->setCategoryIds(array(2,3)); //assign categories to product
//$downloadableproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$downloadableproduct->setMetaTitle('PRODUCT META TITLE');
$downloadableproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$downloadableproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$downloadableproduct->setLinksTitle("Download");
$downloadableproduct->setLinksPurchaseType(0);//links can be purchased separately (0 - NO,1 - YES)
$downloadableproduct->setSamplesTitle("Sample");
$downloadableproduct->save();

$_highfilePath = "1.jpg";
$_samplefilePath = "2.jpg";
$paths = array('highurl' => $_highfilePath, 'sampleurl' => $_samplefilePath);
$samplefile[] = array(
  'file' => $_samplefilePath,
  'name' => $_samplefilePath,
  'size' => filesize($_samplefilePath),
  'status' => 'new'
);
$linkfile[] = array(
  'file' => $_highfilePath,
  'name' => $_highfilePath,
  'size' => filesize($_highfilePath),
  'status' => 'new'
);
$linkFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(),Mage_Downloadable_Model_Link::getBasePath(),$linkfile);
$linkModel = Mage::getModel('downloadable/link')->setData(array(
  'product_id' => $downloadableproduct->getId(),
  'sort_order' => 0, //set link order
  'number_of_downloads' => 0, // set numbers of download (0 - unlimited)
  'is_shareable' => 2, // shareable download link (0 - NO,1 - YES,2 - Use config) 
  'link_url' => '',
  'link_type' => 'file', //download link type url,file
  'link_file' => json_encode($linkfile),
  'sample_url' => 'http://www.site.com/1.jpg', //set sample file url
  'sample_file' => '', 
  'sample_type' => 'url', //download sample type url,file
  'use_default_title' => false, //title assign by user or not
  'title' => 'DOWNLOAD LINK TITLE',
  'default_price' => 0,
  'price' => 10, //add price for download links
  'website_id' => $downloadableproduct->getStore()->getWebsiteId(),
));
$linkModel->setLinkFile($linkFileName)->save();

$sampleFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(),Mage_Downloadable_Model_Link::getBasePath(),$samplefile);
$sampleModel = Mage::getModel('downloadable/sample')->setData(array(
  'product_id' => $downloadableproduct->getId(),
  'sort_order' => 0, //set sample order
  'sample_url' => 'http://www.site.com/1.jpg', //set sample file url
  'sample_file' => '', 
  'sample_type' => 'url', //sample file type url,file
  'title' => 'SAMPLE LINK TITLE',
  'website_id' => $downloadableproduct->getStore()->getWebsiteId(),
));
$sampleModel->setSampleFile($sampleFileName)->save();

Solve Re-indexing Error `Cannot initialize the indexer process` in Magento

If you have a Magento store than whenever you changes in attributes or product or category settings than must re-indexing data for regenerate all products URL and relation with others in website.Re-indexing website data from Admin panel  System -> Index Management.
But sometimes seen error "There was a problem with re-indexing process" or "Cannot initialize the indexer process" and all data not re-indexing mostly category flat data,product flat data.This error because of products,categories or stores and execution time.
Solve this error with follow one or more of below solutions.Must backup of your website with database before applying any method.

#Solution - 1

 

Enter into phpMyAdmin and find all tables with `PREFIX_catalog_product_flat_%` and `PREFIX_catalog_category_flat_store_%` truncate all tables and than after clear Magento caches and than try to re-indexing data


#Solution -2

 

This type of error because of large database and small execution time so increase execution time by write below code in .htaccess file.
   php_value memory_limit 256M  
   php_value max_execution_time 18000
You can also increse memory limit by writing below code in index.php file
   ini_set("memory_limit","256M");
   ini_set('max_execution_time',18000);

 

#Solution -3

 

Create new reindex.php file in magento root folder and add below code on that file.

<?php  
 require_once 'app/Mage.php';  
 $app = Mage::app('admin');  
 umask(0);  
 for ($index = 1; $index <= 8; $index++) {  
     $process = Mage::getModel('index/process')->load($index);  
     $process->reindexAll();  
 }
 ?>
than clear all caches and run file on browser as http://www.YOURSITE.com/reindex.php you can also use below shell script for run this file.
php shell/indexer.php reindex all

 

#Solution -4

 

 Enter into magento root directory clear all folder in var/ directory and set file permission as '777' including all sub folders.than run below two query in phpMyAdmin according to database prefix.
    DELETE cpop.* FROM catalog_product_option_price AS cpop
    INNER JOIN catalog_product_option AS cpo
    ON cpo.option_id = cpop.option_id
    WHERE
    cpo.type = 'checkbox' OR
    cpo.type = 'radio' OR
    cpo.type = 'drop_down';
    
    DELETE cpotp.* FROM catalog_product_option_type_price AS cpotp
    INNER JOIN catalog_product_option_type_value AS cpotv
    ON cpotv.option_type_id = cpotp.option_type_id
    INNER JOIN catalog_product_option AS cpo
    ON cpotv.option_id = cpo.option_id
    WHERE
    cpo.type <> 'checkbox' AND
    cpo.type <> 'radio' AND
    cpo.type <> 'drop_down';
After execute query clear all caches and re-indexing data.

 

#Solution -5

 

Enter into phpMyAdmin and find table `PREFIX_catalog_category_product_index`drop table from database (Disable foreign key using "SET FOREIGN_KEY_CHECKS=0").
Reset foreign key using "SET FOREIGN_KEY_CHECKS=1"than run below code in phpMyAdmin.
    ALTER TABLE `catalog_category_product_index`
    ADD CONSTRAINT `FK_CATALOG_CATEGORY_PROD_IDX_CATEGORY_ENTITY` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity_id`) ON DELETE CASCADE ON UPDATE CASCADE,
    ADD CONSTRAINT `FK_CATALOG_CATEGORY_PROD_IDX_PROD_ENTITY` FOREIGN KEY (`product_id`) REFERENCES `catalog_product_entity` (`entity_id`) ON DELETE CASCADE ON UPDATE CASCADE;
After execute query clear all caches and re-indexing data.

Sunday, November 22, 2015

Change Current Website Language in Drupal


Drupal is an open source Content Management System based on PHP for creating a website to easily manage content, user and pages for development. For each site language is most important according to website locality and information.
When you install new Drupal than must display selection for choose site language. From there you can select language and create website in that language, but if you create website in English and then after you want to convert that into another language then you can easily convert using the Drupal admin panel.
Here below given example for convert English to French. Just follow as below steps for all other language translation.
  • First login to Drupal admin panel if not login (using http://www.yourdomain.com/user or http://www.yourdomain.com/admin)
  • Go to Modules and enable `Locale` module from CORE modules if disable.
  • Go to Configuration-> REGIONAL AND LANGUAGE-> Languages where display list of all installed languages.
  • Click on `Add language` link at top.
  • Select `PREDEFINED LANGUAGE` from selection and click on Add Language button (For French select "French (Français)") after installation success message display there.
  • Now go to http://localize.drupal.org pick language and click on co there button (for French click French and click on button on sidebar)
  • From there display language po file according to Drupal version in Drupal core download that according to your Drupal version (Ex. Download 7.XX for Drupal 7.XX version)
  • Go to Configuration-> REGIONAL AND LANGUAGE-> Translate interface in Drupal admin panel.
  • Click on Import tab at top of page.
  • Now choose po file download from Drupal localize with associate Drupal language.
After importing file new language installed into your Drupal website.configure language from Configuration-> REGIONAL AND LANGUAGE-> Languages and set French as default instead of English for complete website and its content translate into English to French.
In Translate interface Translate tab you can see all core words translation into local language. Here you can change that translation word according to use. During coding whoever you add new text with using `t('XXX')` than XXX word display there for translation. See below video for translating Drupal website one language to another language.

Monday, November 9, 2015

Add a Custom Attribute to the Category in Magento


Magento use for creating an e - commerce website so in that category is the most important functionality. When you install new Magento than there is one category named “Default Category” assign and all new categories and subcategories. We select a product category, so that a product display in associate category in Magento. So all products display in the website according to category and all category display in the Magento main menu.
In Magento category, there are some default fields provide by Magento like Name, Description, Image, Thumbnail Image, Meta Keywords and Description. When you fill the details that its display on front category page according to a filed location.
Sometimes you need an extra category filed like extra category images, link page or any date or text field so you can do with simple creating PHP file in a Magento root folder or anywhere with call “Mage.php” file for use Magento functions. Here below code for adding extra category image field with instruction for another field

require_once "app/Mage.php";
if (!Mage::isInstalled())
{
 echo "Application is not installed yet, please complete install wizard first.";
 exit;
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$installer = new Mage_Eav_Model_Entity_Setup('core_setup'); 
$installer->startSetup();
$attribute  = array(
 'type' => 'varchar', //datetime,decimal,int,static,text,varchar
 'label'=> 'Category Image 1', //custome field label
 'input' => 'image', //date,image,media_image,gallery,multiselect,price,select,textarea,text,weight
  /*
   for date select type='datetime'
   for image/media_image/gallery select type='varchar'
   for price/weight select type='decimal'
  */
 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
 'default' => '1', //set default value
 'source'  => 'catalog/category_attribute_source_sortby', //select model for select and multiselect dropdown values
 /*
 for date 'eav/entity_attribute_backend_datetime'
 for YES/NO selection 'eav/entity_attribute_source_boolean'
 for page layout selection 'catalog/category_attribute_source_layout'
 for ENABLE/DISABLE selection 'catalog/product_status' 
 */
 'backend' => 'catalog/category_attribute_backend_image', //select backend model for save data
 /*
 for image/media_image 'catalog/category_attribute_backend_image'
 for date 'eav/entity_attribute_backend_datetime'
 for price 'catalog/product_attribute_backend_price'
 for gallery 'catalog/product_attribute_backend_media'
 */
 'required' => false, //is required or not
 'sort_order' => 1, //set order
 'group' => "General Information" //General Information,Display Settings,Custom Design
);
$installer->addAttribute('catalog_category', 'category_image_1', $attribute);
$installer->endSetup();

When you run below code file than new category fields added to your Magento admin panel. You can see on catalog->categories and edit any category. If you didn’t see them clear all caches run compile and then check again.
Now it’s also important for display or getting extra field value in front. For this, just use below code according to category id and extra field name assign while creating new in below code.

$category_id = '3'; //enter category id for get custome field data
$cat = Mage::getModel("catalog/category")->load($category_id);
echo $cat->getData('category_image_1');
//for image get full path
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/category/'.$cat->getData('category_image_1');