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

Monday 7 March 2016

How to add auto generate product code in magento


How to add auto generate product code in magento

Kindly follow below steps to create auto product code in magento.


First we need to add new column in `catalog_product_entity` table. To add new column kindly add below code in any module setup file.

For example :

I am using 'Banner' module in mysite so i put below code in app\code\local\Setblue\Banner\sql\banner_setup\mysql4-install-0.1.0.php

before you put below code you must take backup of that code of that file or just comment that code. then put below code in that file


$installer = Mage::getResourceModel('catalog/setup','catalog_setup');

$installer->startSetup();

$installer->getConnection()->addColumn(
    $installer->getTable('catalog/product'),
    'auto_code',
    array(
        'type'    => Varien_Db_Ddl_Table::TYPE_TEXT,
        'length'  => 255,
        'comment' => 'Auto Generate Code'
    )
);

$installer->addAttribute(
    'catalog_product',
    'auto_code',
    array(
        'label' => 'Auto Generate Code',
        'type'  => 'static'
    )
);

$installer->endSetup();

Now Remove Banner(Your module) module entry from 'core_resource' table. So we can run banner module setup file.

After that you must run that module (Ex. Banner) from admin panel.

Now 'auto_code' field is added into table `catalog_product_entity`.

Now we need to execute SQL Trigger when new product will inserted into database from manually (admin panel) or importing product sheet.

Follow the following steps for the same.

Add trigger code on 'catalog_product_entity_decimal' table.

1. Go to phpmyadmin and Select your database and open table 'catalog_product_entity_decimal.

2. Now click on 'Triggers' Option.and click on 'Add trigger'.

3. Trigger name : Enter trigger name (any) like 'Auto Code trigger'

4. Table : Select table `catalog_product_entity_decimal` from trigger popup. it means on which table you want fire trigger.

5. Time :  After (it means it will fire after product added into `catalog_product_entity_decimal` table)

6. Event : Insert (it means it will fire after product inserted into `catalog_product_entity_decimal` table)

7. Definition : we need to add below code.

   UPDATE catalog_product_entity SET auto_code = CONCAT('FP-',new.entity_id) where entity_id = new.entity_id

  in this 'FP-' this is static prefix before auto increment number.and entity_id is product number(primary key)

8. Definer : optional


Now Insert a product and check the entry.

That's it. Enjoy Chandresh Rana's coding... 

Friday 5 February 2016

How to get sub-category by category id in Magento


How to get sub-category by category id in Magento

Try to use below code for subcategories in magento

$subcategoryCollection = Mage::getModel('catalog/category')
 ->getCollection()
 ->addAttributeToFilter('parent_id', 35);
foreach($subcategoryCollection as $_subcategoryCollection)
 {
  $categoryId = $_subcategoryCollection->getEntityId();
  $categoryName = Mage::getModel('catalog/category')->load($categoryId);
  $categoryName->getName();
 }

Saturday 30 January 2016

The PDO extension is required for this adapter but the extension is not loaded Magento


Generally people getting below error after making php.ini file at magento root folder.

"The PDO extension is required for this adapter but the extension is not loaded";i:1;s:2191:"#0 /home/aakrutiw/public_html/mangonis.com/lib/Zend/Db/Adapter/Abstract.php(248);

Kindly add the following in php.ini file which is located in magento root folder

extension=pdo.so;
extension=pdo_sqlite.so;
extension=sqlite.so;

extension=pdo_mysql.so;

Monday 18 January 2016

How to remove decimal from product price in magento


How to remove decimal from product price in magento

Kindly go to app/code/core/Mage/Directory/Model/Currency.php // you can move this file in local folder too

Find the following

public function format($price, $options = array(), $includeContainer = true, $addBrackets = false)
 {
    return $this->formatPrecision($price, 2, $options, $includeContainer, $addBrackets);
 }

And Replace it from below

public function format($price, $options = array(), $includeContainer = true, $addBrackets = false)
 {
    return $this->formatPrecision($price, 0, $options, $includeContainer, $addBrackets);
 }

Now go to js/varien/js.js

Find the following

var precision = isNaN(format.precision = Math.abs(format.precision)) ? 2 : format.precision;
var requiredPrecision = isNaN(format.requiredPrecision = Math.abs(format.requiredPrecision)) ? 2 : format.requiredPrecision;

And Replace it from below

var precision = 0;
var requiredPrecision = 0;


That's it. Enjoy Chandresh rana's Coding... :)

Monday 11 January 2016

How to add buynow button on product page in magento


How to add buynow button on product page in magento

Kindly open app/design/frontend/package/theme/template/catalog/product/view.phtml

Add below line into <form> Tag

<input type="hidden" name="buy_now" id="buy_now" value="" />

Put below button at anywhere where you want

<button type="button" onclick="jQuery('#buy_now').val('buy_now');productAddToCartForm.submit(this)" class="btn btn-block btn-express-buynow"><i class="cart-icon-white m-r-sm v-middle"></i>Buy Now</button>

Now open app/code/core/Mage/Checkout/controllers/CartController.php

Change the code as below instructions

Put below line in _goBack() function at very first

$buy_now = $this->getRequest()->getParam('buy_now');

FInd the line in _goBack() function $this->getResponse()->setRedirect($backUrl); and replace this line as below code

    if (!empty($buy_now)) {
        $this->_redirect('onepagecheckout'); // If you are using onepagecheckout or use this $this->_redirect('checkout/onepage/')
    }else{
        $this->getResponse()->setRedirect($backUrl);
    }

That's it. Enjoy Chandresh rana's Coding...

Saturday 2 January 2016

Get category name by category id in magento


Get category name by category id in magento

$category = Mage::getModel('catalog/category')->load($categoryId);

// category name
$categoryName = $category->getName();

// category url
$categoryUrl = $category->getUrl();

Wednesday 28 October 2015

Send contact email programmatically in magento


Send contact email programmatically in magento

$mageFilename = '../app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();

$post = array('name'=>'Chandresh','email'=>'chand.4rana@gmail.com','telephone'=>'9222888120','comment'=>'This is testing email');
$postObject = new Varien_Object();
$postObject->setData($post);
$translate = Mage::getSingleton('core/translate');
$mailTemplate = Mage::getModel('core/email_template');
/* @var $mailTemplate Mage_Core_Model_Email_Template */

try{
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig('contacts/email/email_template'),
Mage::getStoreConfig('contacts/email/sender_email_identity'),
Mage::getStoreConfig('contacts/email/recipient_email'),
null,
array('data' => $postObject)
);
$translate->setTranslateInline(true);
echo Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.');

}catch(Exception $e){

echo Mage::helper('contacts')->__('Unable to submit your request. Please, try again later');

}

Tuesday 27 October 2015

Magento Display products from the category on the home page


Magento Display products from the category on the home page

In Magento admin panel go to CMS> Pages>Home page
Open the Content tab and paste the following code into the html code block :

{{block type="catalog/product_list" category_id="3" template="catalog/product/list.phtml"}}

Make sure the category_id="3" value is your category ID and Save the CMS.

Monday 26 October 2015

How to get Random collection from any module in magento


How to get Random collection from any module in magento

You have to create a new function in your module’s collection class

(YourNamespace/YourModule/Model/Mysql4/YourModule/Collection.php)

public function setRandomOrder()
{
    $this->getSelect()->order(new Zend_Db_Expr('RAND()'));
    return $this;
}

$collection = Mage::getModel('yourmodule/yourmodule')
                    ->getCollection()
                    ->setRandomOrder();

Thats it.... Enjoy Chandresh rana's Coding... :)

Friday 2 October 2015

Product images not display after move site to new server magento


Product images not display after move site to new server magento

I also had this issue in past, When i move my magento site local to new server suddenly images disappear on front end and back end too.
After very debugging i got the below solution.

In my case i went to /public_html/media/catalog/product and renamed all the capital letters to lower case.

If your all directory has lower case then renamed it to capital letters.

After this my all products displays as it is.

I hope it will help you.

Wednesday 30 September 2015

Magento my module extension sql installer script not run


Magento my module extension sql installer script not run

Following are the possible reasons for not running your module sql script

(1) Open the database and check in core_resource table, Find your module setup record like "customlink_setup" and delete that record if you found and try again.
(2) Open the database and check in eav_attribute table, Find your attribute id like "thumbnail_link" in table and delete it if you found.
(3) Check Your module version in config.xml file and mysql installer file version number must be same

I Hope It will help you.

Tuesday 29 September 2015

How to add custom field or attribute in category magento backend


How to add custom field or attribute in category magento backend

Here i have make a module for add custom field/attribute in category. In my module example user can add thumbnail link in category. In additional you can also create your own attribute from my example module. So now lets start for module.

First of all create Setblue_Chand.xml file and save it to app/etc/modules/Setblue_Chand.xml and paste below code :

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


Next up, lets create another XML file Config.xml and save it to  app/code/local/Setblue/Chand/etc/config.xml and paste below code :

<?xml version="1.0"?>
<config>
  <modules>
    <Setblue_Chand>
      <version>0.0.1</version>
    </Setblue_Chand>
  </modules>
    <global>
      <resources>
          <customlink_setup>
            <setup>
              <module>Setblue_Chand</module>
              <class>Mage_Eav_Model_Entity_Setup</class>
            </setup>
            <connection>
              <use>default_setup</use>
            </connection>
          </customlink_setup>
      </resources>
    </global>
</config>

Now create mysql4-install-0.0.1.php file and save it to app/code/local/Setblue/Chand/sql/customlink_setup/mysql4-install-0.0.1.php and paste below code :

<?php
    $installer = $this;
    $installer->startSetup();
    $attribute  = array(
        'type' => 'text',
        'label'=> 'Thumbnail Link',
        'input' => 'text',
        'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
        'visible' => true,
        'required' => false,
        'user_defined' => true,
        'default' => "",
        'group' => "General Information",
        'sort_order' => 6
    );
    $installer->addAttribute('catalog_category', 'thumbnail_link', $attribute);
 
    $installer->endSetup();
?>

Note: If above module already install in your site then delete the module entry from core_resources table and check.

That's it. Now clear your cache and check the General Information in category in admin panel. The page should look like this :


Monday 28 September 2015

How to get Custom Options Programmatically in Magento


How to get Custom Options Programmatically in Magento

I have given here only array of custom option. You can use this array for multipurpose. Fetch the value from array and show it as your wish.


$product = Mage::getModel("catalog/product")->load($_product->getId());
$custopOption = $product->getOptions();
foreach($custopOption as $optionKey => $optionVal){
    foreach($optionVal->getValues() as $valuesKey => $valuesVal){
        echo $optionVal->getId();
    }
}

How to redirect in magento to any page


How to redirect in magento to any page

Here i will explain you how to redirect any page in magento. Just write below code in your magento file...

$location = "http://chandreshrana.blogspot.in/";
Mage::app()->getResponse()->setRedirect($location);

Friday 25 September 2015

Magento Shopping Cart Price Rule that excludes discounted products


Magento Shopping Cart Price Rule that excludes discounted products

It is obvious things that coupon code should not apply on discount products. But there is no rule and conditions for that in magento. Here i have use a small trick and its work for me. I hope it will be use for needed people also.

Go to shopping cart price rule and click on Actions tab and follow the below image condition.


Monday 21 September 2015

Get product collection of wishlist magento


Get product collection of wishlist magento

Put the below code in anywhere of your site and get the collection of customer wishlist.

<?php
    $customer = Mage::getSingleton('customer/session')->getCustomer();
    if($customer->getId()){
        $wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
        $wishlistItems = $wishlist->getItemCollection();
    }else{
        $wishlistItems = array();
    }
?>

<?php if(count($wishlistItems) > 0): ?>
    <div class="checkout_body" style="padding: 8px;">
        <ul class="order_summ">
            <?php foreach ($wishlistItems as $item): ?>
                <?php $_product = Mage::getModel('catalog/product')->load($item->getProduct()->getId()); ?>
                <li>
                    <div class="cart_product">
                        <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize(74,97); ?>" alt="" class="img-responsive">
                    </div>
                    <div class="cart_product_desc">
                        <div class="name_ellipsis"><a href="<?php echo $_product->getProductUrl() ?>"><?php echo $_product->getName(); ?></a></div>
                        <div>Quantity : <?php echo $item->getQty(); ?></div>
                        <div>Unit Price : <span class="unit_price"><?php echo Mage::helper('core')->currency($_product->getFinalPrice(),2); ?></span></div>
                    </div>
                    <div class="cart_product_edit">
                        <button onclick="setLocation('<?php echo $this->helper('wishlist')->getRemoveUrl($item); ?>')">
                            <img src="<?php echo $this->getSkinUrl("images/delete_icon.png"); ?>" />
                        </button>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php else: ?>
    <div style="padding: 8px;" class="checkout_body">
      There are no products in the wishlist.
    </div>
<?php endif; ?>  

Friday 18 September 2015

How to redirect last page after login in magento


How to redirect last page after login in magento

In my case Go to Admin => System => Configuration => Customer Configuration => Login Options => "Redirect Customer to Account Dashboard after Logging in" set it "No".
After this Customer will stay on the current page.

Get total items count in cart magento


Get total items count in cart magento

Here is a simple code to get the items count in cart magento. The below code is return total items count not total quantity counts. For example skuA has 10 qty in cart and skyB has 2 qty in cart then below code return 2 counts becoz there are total 2 products/items in cart.

<?php
$totalItems = Mage::helper('checkout/cart')->getItemsCount();
 echo $totalItems;
?>