Thursday, 25 April 2013

Magento Most popular products for each category


<?php $get_cat = Mage::getSingleton('catalog/layer')->getCurrentCategory()->getId();

$category = Mage::getModel('catalog/category')->load($get_cat);
$products = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty() //total number of quantities ordered
    ->addAttributeToSelect('*') //get all attributes
    ->setOrder('ordered_qty', 'desc') //most ordered quantity products first
    ->addCategoryFilter($category);

foreach ($products as $prod){

 if($prod->getIsActive()){
echo $this->htmlEscape($prod->getName());
echo "<br>";
 }

}

?>

Thursday, 18 April 2013

Magento Introduction and advantages


Magento
  Magento was first launched on March 31, 2008. It was developed by Varien (now Magento Inc) with help from the programmers within the open source community but is owned solely by Magento Inc.. Magento was built using the Zend Framework.It uses the entity-attribute-value (EAV) database model to store data. It should seprated into three types (Magento Enterprise Edition , Magento Community Edition , Magento Professional Edition),Mainly all magento users used MEE and MCE
Magento Enterprise Vs Community
There are currently two editions of Magento available, Magento Enterprise Edition and Magento Community Edition. Both editions of Magento are valuable, however, they are meant for different audiences. You might have questions about what the two editions are, why both editions need to exist and what the differences between them are. This FAQ will help you get answers to these questions and set you on the right path for eCommerce success.

Magento Enterprise Edition :
MEE is the complete eCommerce solution for businesses that are ready to take full advantage of their online channel. This solution combines an unrivaled feature set with world-class support and virtually infinite flexibility, at a fraction of the price charged by competitive platforms.for MEE Magento provide technical support.

Magento Community Edition :
Development of the MCE continues at a rapid pace through this model, providing a basic and powerful solution for small shops looking for a state-of-the-art eCommerce platform.Magento Community Edition is open source software and can be downloaded for free.
Developers can modify the core code and add features and functionality by installing extensions from the Magento Connect marketplace. MCE to run their stores will want to have access to their own Magento experts, since Magento does not provide technical support for this software.
MCE is a feature-rich, professional open-source eCommerce solution that offers merchants complete flexibility and control over the look, content, and functionality of their online store. Magento’s powerful marketing, search engine optimization and catalog-management tools give merchants the power to create ecommerce sites that are tailored to their unique business needs.
Current Version
Magento Enterprise Edition
Magento Communtity Edition
1. Latest Magento Enterprise is 1.12.0.2
1.Latest Magento Communti 1.7.0.2

Upcoming Version
Magento Enterprise Edition
Magento Communtity Edition
1. Latest Magento Enterprise is 1.13
1.Latest Magento Communti 1.8

Latest Version Advantages :
MEE 1.12.0.2 :
  • HTM5
  • Visitors segment
  • Expandable rule-based product-relations
  • Speedier checkout flow
  • Autogenerated of coupon codes
  • Multiple Wishlist
  • Layered Navigation price Enchnacement
  • Customer Group pricing
  • Add to cart by SKU
  • CMS page hierarachy Enchancements
  • Functional Improvements
  • Backup and Rollback
  • Payment Bridge updates
  • Capthca
Additional Modules :
There are some interesting additional modules in the Enterprise Edition:
  • Private sales, which allows retailers to restrict access to stores and offers to selected customers, and to manage the launch and termination of private sales.
  • Access to the back-end can be controlled at the website or store level, where in the Community Edition you can only restrict access at the function / module level. This is very useful for multi-store Magento installations.
  • The ability to merge and combine content from one store with another, and to use this facility to create a content staging environment. Instead of having 2 instances of Magento (as we do with some clients at present) one for the next catalog, one for the current catalog, you could do all this in one installation, which is a very interesting development, especially for larger retailers. A full audit trail of all admin actions. Very useful.
  • Gift card and store card functionality which allows electronic gift cards to be sold and used on Magento stores.
  • Store credit functions, for example allowing a contact centre to make an ex gratia payment to a shopper in the event of a complaint.
  • Enhanced security in line with PCI recommendations, with things like password expiry for administrators.
MCE 1.7.0.2
  • HTML 5
  • PHP-FPM for PHP management
  • APC for PHP caching
  • Autogenerated of coupon codes
  • Layered Navigation price Enchnacement
  • Customer Group pricing
  • AjaXplorer for file server management
  • Reset API's support
  • European union VAT-ID validation
  • Built on Amazon Linux (CentOS) for security
  • Capthca
  • Backup and Rollback

Improvements MCE

  • Added the functionality for creating nested field sets in the System configuration
  • Implemented the support for the extended and shared configuration fields
  • Added the ability to define dependencies between fields from different field sets

Changes

  • Moved PayPal configuration to the Payment Methods menu
  • Set the default value of the cUrl VERIFYPEER option to TRUE for PayPal and added the ability to change this value
  • Changed the design and position of the configuration field tooltips

Fixes

  • Fixed: Inability of SOAP v2 API use in non WS-I compatible mode in the applications written in languages with strong typing
  • Fixed: In some cases comments history tab on order does not contain information about customer notifications
  • Fixed: Several potential security vulnerabilities





Wednesday, 17 April 2013

Import Products Programmatically

 Import Products Programmatically ,Get Products image from external URL , Update if product SKU id exists and redirect to particular page



<?php
$product = $_REQUEST;
include_once("app/Mage.php");
Mage::app();

       $newproduct = Mage::getModel('catalog/product');
       $sku = $product['product'];
       $quant = $product['available'];
       $productId = Mage::getModel('catalog/product')->getCollection();
    $skuid = array();
        foreach ($productId as $check) {
           $i = $i+1;
    $skuid[] = $check->getSku();
        }  
        if (!in_array($sku,$skuid)) {
        $newproduct->setSku($product['product']);
       
        $newproduct->setTypeId('simple');
        $newproduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $newproduct->setStatus(1);
        $newproduct->setWeight($product['weight']);
        $newproduct->setTaxClassId(0);
        $newproduct->setWebsiteIDs(array(1));
        $newproduct->setStoreIDs(array(1));
        $newproduct->setStockData(array(
            'is_in_stock' => 1,
            'qty' =>$quant ,
            'manage_stock' => 1
        ));
      
        $newproduct->setAttributeSetId(4);
        $newproduct->setName($product['product']);
        $newproduct->setCategoryIds(array(2,3)); // array of categories it will relate to
        $newproduct->setDescription($product['productText']);
        $newproduct->setShortDescription($product['productText']);
        $newproduct->setBrand($product['brand']);
        $newproduct->setBrandtext($product['brandText']);
        $newproduct->setList($product['list']);
        $newproduct->setPrice($product['price']);
        $newproduct->setCat($product['category']);
        $newproduct->setCategorytext($product['categoryText']);
        $newproduct->setYear($product['year']);
        $newproduct->setMake($product['make']);
        $newproduct->setModel($product['model']);
        $newproduct->setCore($product['core']);
        $newproduct->setShips($product['ships']);
        $newproduct->setApplication($product['application']);
        $newproduct->setCatalogproduct($product['catalogProduct']);
        $newproduct->setPartnersession($product['partnerSession']);
   
        $from = $product['imageurl'] ;
        $prod = $product['imageurl'];
        $prod1 = explode("/",$prod);
        $prod2 = end($prod1);
        $to = "/home/domains/spd1/media/import/".$prod2 ;
        copy($from,$to);
        $fullImagePath = "/home/domains/spd1/media/import/".$prod2;
        $visibility = array (
           'thumbnail',
           'small_image',
           'image'
        );
        $newproduct->addImageToMediaGallery( $fullImagePath, $visibility, true, false);

    } else {
   
        $newproduct1 = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
        $newproduct1->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $newproduct1->setStatus(1);
        $newproduct1->setWeight($product['weight']);
        $newproduct1->setTaxClassId(0);
        $newproduct1->setAttributeSetId(4);
        $newproduct1->setName($product['product']);
        $newproduct1->setCategoryIds(array(2,3)); // array of categories it will relate to
        $newproduct1->setDescription($product['productText']);
        $newproduct1->setShortDescription($product['productText']);
        $newproduct1->setBrand($product['brand']);
        $newproduct1->setBrandtext($product['brandText']);
        $newproduct1->setList($product['list']);
        $newproduct1->setPrice($product['price']);
        $newproduct1->setCat($product['category']);
        $newproduct1->setCategorytext($product['categoryText']);
        $newproduct1->setYear($product['year']);
        $newproduct1->setMake($product['make']);
        $newproduct1->setModel($product['model']);
        $newproduct1->setCore($product['core']);
        $newproduct1->setShips($product['ships']);
        $newproduct1->setApplication($product['application']);
        $newproduct1->setCatalogproduct($product['catalogProduct']);
        $newproduct1->setPartnersession($product['partnerSession']);
   
            try {
                if (is_array($errors = $newproduct1->validate())) {
                    $strErrors = array();
                    foreach($errors as $code=>$error) {
                    $strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
                    }
                    $this->_fault('data_invalid', implode("\n", $strErrors));
                }

                $newproduct1->save();
                } catch (Mage_Core_Exception $e) {
                $this->_fault('data_invalid', $e->getMessage());
                } 
    }

    try {
        if (is_array($errors = $newproduct->validate())) {
            $strErrors = array();
            foreach($errors as $code=>$error) {
                $strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
            }
            $this->_fault('data_invalid', implode("\n", $strErrors));
        }

        $newproduct->save();
    } catch (Mage_Core_Exception $e) {
        $this->_fault('data_invalid', $e->getMessage());
    }
   
   
echo $extra = strtolower($product['product']);
 
header("Location: redirect path");

?>

Thursday, 21 March 2013

Get particular category all product images

<?php

$cat_id = 513;  //category id
$category = Mage::getModel('catalog/category')->load($cat_id);
$collection = $category->getProductCollection()->addAttributeToSort('position');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
?>
<ul id="mycarousel" class="jcarousel-skin-tango">
<li>
<?php
foreach ($collection as $product) {
?>
   
<img src="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(150, 118); ?>"  alt="<?php echo $this->htmlEscape($product->getName()) ?>" />
 </li>
</ul>
<?php    
  
}

?>

Display all sub categories via phtml file



<div>
<?php
    $children = Mage::getModel('catalog/category')->getCategories(37);
    foreach ($children as $category):
        $category = Mage::getModel('catalog/category')->load($category->getId());
        echo '<li><a href="' . $category->getUrl() . '">' . $category->getName() . '</a></li>';
            $child = Mage::getModel('catalog/category')->getCategories($category->getId());
            foreach ($child as $cat):
                $cat = Mage::getModel('catalog/category')->load($cat->getId());
                echo '<li><a href="' . $cat->getUrl() . '">' . $cat->getName() . '</a></li>';
            endforeach;
    endforeach;
?>
</div>

onchange select option redirect to another page

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>
 
And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>
 
 
for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Monday, 11 March 2013

Install Wordpress with wamp




  1. Download wordpress here http://wordpress.org/download/
  2. Stored that wordpress folder in wamp/www
  3. Then give 0777 (Read and write )permission for whole wordpress folder
  4. Create Database in mysql (eg - DB name: test)
  5. click create configuration button (for create config file)
  6. Then click let's go button instead of next button
  7. Then give Database name(eg : name as test),mysql username,password,host name and if you need prefix (please give prefix values that shows in before table name)- click next button
  8. Then click “Run the install ” button for further process
  9. Then give site name ,username,password,confirm password and email id ,click install button
  10. Then click the login button it will redirect to admin (back end )page ,in that page Back button click it redirect to home page


Install Joomla with wamp



  1. Download Joomla files in http://www.joomla.org/download.html
  2. Stored that joomla folder in wamp/www
  3. Then give 0777 (Read and write )permission for whole joomla folder
  4. Please check all wamp services are in enable mode,if you want to check all service enable (wamp server in Quick launch toolbar shows in green color)
  5. Create Database in mysql (eg - DB name: joomla)
  6. select language because joomla supports multiple language(so choose language)
  7. Then Preinstallation files are displayed-no need for change
  8. Then Licence page – click next
  9. Then Database Configuration
    Select Database type as Mysql
    Host name -> Localhost
    Give username, password for mysql
    Give Database name
    click next button
  10. FTP Configuration
    This step is not necessary for local setup,if you could integrate with other server means it is necessary
  11. Main Configuration
    Give site name,admin mail ID,admin username,admin password,confirm password
    if u want ti install sample data click install sample data button(else it is not necessary)
    click next button
  12. It is the last step if you want to remove the installation folder please click remove installation folder
  13. Then click the right top buttons for going to frontend and backend

Monday, 4 March 2013

simple javascript validation for textbox



<html>
<head>

<script type="text/javascript">
<!--
var validNums = '0123456789.()+- ';
var validLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -';

function validateKeyPress(e, validSet)
{
    var key;
    var keychar;
       
    if(window.event || !e.which) // IE
        key = e.keyCode; // IE
    else if(e)
        key = e.which;   // Netscape
    else
        return true;     // no validation

    keychar = String.fromCharCode(key);
    validSet += String.fromCharCode(8);

    if (validSet.indexOf(keychar) < 0)
      return false;

    return true;
}
//-->
</script>

</head>
<body>
    <form name="myForm">
        <input type="text" size="50" onKeyPress="return validateKeyPress(event, validLetters)" />
    </form>
</body>
</html> 

Tuesday, 26 February 2013

Magento billing and shipping details in sucess.phtml page


Use this code in sucess.phtml page


$order =  Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
$shipping_address_data    = $order->getShippingAddress();
$billing_address_data   = $order->getBillingAddress();


    echo "customer ID".$shipping_address_data['customer_id'];
    echo "customer firstname".$shipping_address_data['firstname'];
    echo "customer lastname".$shipping_address_data['lastname'];
    echo "customer street".$shipping_address_data['street'];
    echo "customer city".$shipping_address_data['city'];
    echo "customer region".$shipping_address_data['region'];
    echo "customer region_id".$shipping_address_data['region_id'];
    echo "customer postcode".$shipping_address_data['postcode'];
    echo "customer telephone".$shipping_address_data['telephone'];
    echo "customer country_id".$shipping_address_data['country_id'];
  
    echo "Billing customer ID".$billing_address_data['customer_id'];
    echo "Billing customer firstname".$billing_address_data['firstname'];
    echo "Billing customer lastname".$billing_address_data['lastname'];
    echo "Billing customer street".$billing_address_data['street'];
    echo "Billing customer city".$billing_address_data['city'];
    echo "Billing customer region".$billing_address_data['region'];
    echo "Billing customer region_id".$billing_address_data['region_id'];
    echo "Billing customer postcode".$billing_address_data['postcode'];
    echo "Billing customer telephone".$billing_address_data['telephone'];
    echo "Billing Billing Add Country ID".$billing_address_data['country_id'];

Wednesday, 13 February 2013

Magento cache,session folder delete



Please pu this file in magento root and give 777 permission for this file,give any

name for this page

<?php
$xml = simplexml_load_file('app/etc/local.xml', NULL, LIBXML_NOCDATA);

$db['host'] = $xml->global->resources->default_setup->connection->host;
$db['name'] = $xml->global->resources->default_setup->connection->dbname;
$db['user'] = $xml->global->resources->default_setup->connection->username;
$db['pass'] = $xml->global->resources->default_setup->connection->password;
$db['pref'] = $xml->global->resources->db->table_prefix;

clean_var_directory();

function clean_log_tables() {
    global $db;
   
    $tables = array(
        'catalogindex_aggregation',
        'catalogindex_aggregation_tag',
        'catalogindex_aggregation_to_tag',
        'catalogsearch_fulltext',
        'dataflow_batch_export',
        'dataflow_batch_import',
        'log_customer',
        'log_quote',
        'log_summary',
        'log_summary_type',
        'log_url',
        'log_url_info',
        'log_visitor',
        'log_visitor_info',
        'log_visitor_online',
        'report_event'
    );
   
    mysql_connect($db['host'], $db['user'], $db['pass']) or die(mysql_error());
    mysql_select_db($db['name']) or die(mysql_error());
   
    $message = "Working!! 1\nLine 2\nLine 3";

    // In case any of our lines are larger than 70 characters, we should use wordwrap()
    $message = wordwrap($message, 70);
   
    // Send
    mail('jagadckap@gmail.com', 'My Subject', $message);
   
   
    foreach($tables as $v => $k) {
        mysql_query('TRUNCATE `'.$db['pref'].$k.'`') or die(mysql_error());
    }
}

function clean_var_directory() {
    $dirs = array(
        'downloader/.cache/*',
        'downloader/pearlib/cache/*',
        'downloader/pearlib/download/*',
        'var/cache/',
        'var/locks/',
        'var/log/',
        'var/report/',
        'var/session/',
        'var/tmp/'
    );
   
    foreach($dirs as $v => $k) {
        exec('rm -rf '.$k);
    }
}

?>

Tuesday, 5 February 2013

Shipping method comments


 Follow this site it is easy to create Shipping method comments

http://www.demacmedia.com/ecommerce/mini-tutorial-adding-column-to-orders-grid-in-magento-backend/

Monday, 28 January 2013

Easily add Custom field in checkout

Custom field in checkout

URL : http://www.magentocommerce.com/magento-connect/customer-experience/checkout/custom-field-in-checkout-8025.html

 

 

Add Customer Comments In The Checkout

Free Magento Extension – Customer Comments In The Checkout


URL : http://magebase.com/magento-extensions/free-magento-extension-customer-comments-in-the-checkout/

 

Tuesday, 22 January 2013

Magento Shopping Cart All information

I will show you how you can get information about all items in your Magento Shopping Cart. You will see how you can :-

- Get products id, name, price, quantity, etc. present in your cart.
- Get number of items in cart and total quantity in cart.
- Get base total price and grand total price of items in cart.
Get all items information in cart
 
// $items = Mage::getModel('checkout/cart')->getQuote()->getAllItems();
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}
   
Get total items and total quantity in cart

 
$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
 
Get subtotal and grand total price of cart

 
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();

Wednesday, 9 January 2013

Back to Top using jQuery

If you take a look way, way, way down at the bottom of this page, you will see a Back to Top button that scrolls the whole page until it reaches to top. It is a pretty simple effect to add to your site and looks a hundred-times cooler than just using your typical anchor name and link. Getting it all to work takes nothing more than a few lines of jQuery version 1.4.2.

First, we need to create our button/link. I am just going to use an anchor tag and some text:

<a href="javascript:void(0)" class="backtotop">Back to Top</a> 



Next we need to add some jQuery between the <head> tags:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script type='text/javascript'> jQuery('.backtotop').click(function(){ jQuery('html, body').animate({scrollTop:0}, 'slow'); }); </script> 

Remember, you can change the speed by replacing slow with a numerical value. You can also add some easing effects by including the jQuery UI. Read more about easing effects here.

Sunday, 6 January 2013

Magento Error- Can’t Login to Admin Panel

Some times when you try to login your Magento Admin Panel after Magento Installation, nothing happens. That is to say you wouldn’t be able to login admin panel of your store.
magento admin cant login Magento Error  Can’t Login to Admin Panel
So today, we will be sharing solutions to such issue.
Reason of the problem
The main reason of such type of issue is that sometimes Magento fails to store cookies. Usually while working on localhost, people get such type of errors. We have cited following 2 solutions to this problem.

 Solutions

 Solution #1

If you are running Magento on local host using specific server applications like WAMP, XAMPP, AppServ etc.then try to replace “localhot” in your web url with 127.0.0.1.
For e.g.:
Replace
http://localhost/magento/index.php/admin
to
http://127.0.0.1/magento/index.php/admin
In case it doesn’t work for you, then follow the second solution mentioned below:

Solution #2

a)     Go to app/code/core/Mage/Core/Model/Session/Abstract/Varien.php file within your magento directory.

b)    Find the code:

session_set_cookie_params(
 $this->getCookie()->getLifetime(),
 $this->getCookie()->getPath(),
 $this->getCookie()->getDomain(),
 $this->getCookie()->isSecure(),
 $this->getCookie()->getHttponly()
 );
 
and replace with

session_set_cookie_params(
 $this->getCookie()->getLifetime(),
 $this->getCookie()->getPath()
 //$this->getCookie()->getDomain(),
 //$this->getCookie()->isSecure(),
 //$this->getCookie()->getHttponly()
 );
 
c)     Save the file and try to login admin panel

How to Set Up SSL in Magento?

We all know that an online store must have Secure Socket Layer (SSL) as customers use their confidential information such as credit card number etc. to make a purchase on your website. The private SSL certificate is very much vital for any eCommerce website. Even your visitors will also not prefer to buy from your store for being less secure.
Why SSL?
As above mentioned, SSL is very much necessary feature for your Magento Store as it is used to encrypt all communication between the browser and the server so as to ensure that all data goes through a secure (HTTPS) connection.
For all Magento Store merchants, it is strongly advised to implement SSL in their stores. Following are the steps to set up SSL in Magento Store:
Step 1
For Setting up SSL, you must get a SSL certificate first and contact your web host to set up the same for your domain.
Step 2
The next step would be to enable the certificate which can be done by following:
  • Go to Magento Admin area -> System -> Configuration -> Web
  • Define the insecure (non-SSL) and secure (SSL) URLs


SSL Setup Magento How to Set Up SSL in Magento?
In the above image, you can see different fields such as Base URL, Base Link URL etc under “Unsecure” and “Secure” sections. In Base URL fields you need to enter the regular website URL and website URL for SSL Connections. Leave other values unchanged because they’ll be set by script automatically once you’ll enter the Base URL.
Other fields are meant for URLs of the skinmedia and JavaScript folders. Drop Down fields will give options of “Yes” and “No” for allowing SSL Support in frontend and backend of website.
4. Clear your cache.
5. Now check your website frontend. Try to add a product to the cart and checkout. It should take you to https.
Note: Keep in Mind that SSL Connection over HTTPS version would be slow as compared to HTTP. So it is advised to implement it only on those pages which contain or process confidential information.

Magento- Display Products on Home Page with Pagination



If you want to display products on home page of your Magento Store with pagination, then this tutorial is for you. Follow these simple steps to add such functionality in your Magento Store:
  • Go to CMS > Manage Pages and click on the “Home page”.
  • Under the “Design” tab, insert the following code in the “Update Layout XML” field:


<reference name="content">
<block type="catalog/product_list" name="product_list" template="catalog/product/list.phtml">
<action method="setCategoryId"><category_id>3</category_id></action> 
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
</block>
<action method="setToolbarBlockName"><name>product_list_toolbar</name></action> 
</block> 
</reference>

Sunday, 23 December 2012

Simple Cakephp form creation

Form creation in cakephp

first app->controller->Admincontroller



public function category_add ( ) {
        $this->layout = 'admin';  //layout call
        $this->loadModel('Category'); //model call
        if(!empty ($this->request->data)) {
            $category_data = $this->request->data['Category'];
            $image = array();
            $formimage = array('category_image');
            $image = array($category_data['category_image']);
            $file = $this->uploadFiles('img/category', $image,$formimage);
            /* check file upload */
            if(!isset($file['urls'])) { 
                $this->Session->setFlash(implode($file['errors']));
            } elseif(isset($file['urls']) && count($file['urls']) < 1 ) { 
                $this->Session->setFlash(implode($file['errors']));
            } else {
                for($i=0; $i < count($file['urls']); $i++) {
                    $category_data[$formimage[$i]] = $file['urls'][$formimage[$i]];
                }
                if($this->Category->save($category_data)) {
                    $last_id= $this->Category->getLastInsertID();
                    if($category_data['url']) {
                        $this->loadModel('Indexer');
                        $indexer =array();
                        $indexer['Indexer']['item_id']="$last_id";
                        $indexer['Indexer']['type']="Category";
                        $indexer['Indexer']['url']=$category_data['url'];
                    if($this->Indexer->save($indexer)){
                    }
            }
            $this->Session->setFlash('The Category has been addedd successfully');
            $this->redirect(array('action'=>'category_list'));
            } else {
                print_r($this->Category->validationErrors);
                $this->Session->setFlash('The Category was not saved. Please re enter the details');
            }
            }
            /* end Db saved */
        } else {
            $this->render();
        }
    }


second app->Model creation ->Category.php

class Category extends AppModel {
    var $name = "Category";
    public $useTable = 'peeka_category';
    public $primaryKey = 'category_id';
    public $validate = array();

//relation ships(if not need it is not necessary)
    public $hasMany = array(
        'CategoryDeal'=>array(
            'class'=>'CategoryDeal',
            'foreignKey'=>'category_id'
        ),
        'Categorybanner'=>array(
            'class'=>'Categorybanner',
            'foreignKey'=>'category_id'
        ),'Productcatagory'=>array(
            'class'=>'Productcatagory',
            'foreignKey'=>'category_id'
        )
    );
    public $hasOne = array(
        'Indexer'=>array(
            'class'=>'Indexer',
            'foreignKey'=>'item_id',
            'coditions'=>array('Indexer.type'=>'Category')
        )
    );
}



View files app->View->Admin


<?php

    echo $this->Html->script('/js/jQuery.Validate.min.js');
   
    echo $this->Form->create('Category', array('type' => 'file','name'=>'addcategoryform'));

    echo $this->Form->input('category_name', array('label' => 'Category Name','class' => 'required ','id' =>'copy_from','onkeyup'=>'copy_data(this)'));
?>  
<div style="display:none">
<?php
      
   
     echo $this->Form->input('url', array('readonly' => 'true','label' => 'URL','class' => 'required','id' =>'copy_to'));

?>
</div>
<?php
    echo $this->Form->input ( 'category_title' ,array ('label' => 'Category Title','class' => 'required' ) ) ;
   
    echo $this->Form->input('category_image', array( 'type' => 'file','id'=>'img','class'=>'required'));
   
    echo $this->Form->input ( 'category_desc' ,array ('label' => 'Category Descrption','type'=>'textarea','class' => 'required' ) ) ;
   
    echo $this->Form->input('category_url', array('label' => 'Category Link URL','class' => 'required','id' =>'copy_to'));
   
    echo $this->Form->input('meta_keyword', array('label' => 'Meta Keyword'));

    echo $this->Form->input('meta_desc', array('type' =>'textarea','label' => 'Meta Desc'));
   

    echo $this->Form->end('Save Category');


?>