Search This Blog

Tuesday, March 8, 2011

Magento form validation, text validation, url validation

Most important thing besides assigning class names to form in magento is that little piece of JavaScript below the form. Remember to pass form id into the new VarienForm object.

Basically that’s it. Constructing the form this way, automatically makes your form reuse already existing validation code, the one that the rest of the shop is using.

Below is a full list of validate class and its error message that I found in prototype lib.

    * validate-select

Please select an option.

    * required-entry

This is a required field.

    * validate-number

Please enter a valid number in this field.

    * validate-digits

Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.

    * validate-alpha

Please use letters only (a-z or A-Z) in this field.

    * validate-code

Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

    * validate-alphanum

Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.

    * validate-street

Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.

    * validate-phoneStrict

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

    * validate-phoneLax

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

    * validate-fax

Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.

    * validate-date

Please enter a valid date.

    * validate-email

Please enter a valid email address. For example johndoe@domain.com.

    * validate-emailSender

Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

    * validate-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored.

    * validate-admin-password

Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.

    * validate-cpassword

lease make sure your passwords match.

    * validate-url

Please enter a valid URL. http:// is required

    * validate-clean-url

Please enter a valid URL. For example http://www.example.com or www.example.com

    * validate-identifier

Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

    * validate-xml-identifier

Please enter a valid XML-identifier. For example something_1, block5, id-4

    * validate-ssn

Please enter a valid social security number. For example 123-45-6789.

    * validate-zip

Please enter a valid zip code. For example 90602 or 90602-1234.

    * validate-date-au

Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.

    * validate-currency-dollar

Please enter a valid $ amount. For example $100.00.

    * validate-one-required

Please select one of the above options.

    * validate-one-required-by-name

Please select one of the options.

    * validate-not-negative-number

Please enter a valid number in this field.

    * validate-state

Please select State/Province.

    * validate-new-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored.

    * validate-greater-than-zero

Please enter a number greater than 0 in this field.

    * validate-zero-or-greater

Please enter a number 0 or greater in this field.

    * validate-cc-number

Please enter a valid credit card number.

    * validate-cc-type

Credit card number doesn\’t match credit card type

    * validate-cc-type-select

Card type doesn\’t match credit card number

    * validate-cc-exp

Incorrect credit card expiration date

    * validate-cc-cvn

Please enter a valid credit card verification number.

    * validate-data

Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

    * validate-css-length

Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%

    * validate-length

Maximum length exceeded.


http://www.magestore.com/blog/2010/04/09/form-validation-on-magento/



Sunday, March 6, 2011

Magento: How to select, insert, update, and delete data


CRUD (Create Read Update Delete)

Database table named ‘article‘

INSERT DATA

$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'test1,'content'=>'test2.','status'=>0);
$model = Mage::getModel('myarticle/myarticle')->setData($data);
try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();
}

SELECT DATA

$item->getData() prints array of data from ‘article’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('myarticle/myarticle');
$collection = $model->getCollection();
foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDAT

$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'erewr','content'=>'dsfsdf','status'=>1);
$model = Mage::getModel('myarticle/myarticle')->load($id)->addData($data);
try {
        $model->setId($id)->save();
        echo "Data updated successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

DELET

$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('myarticle/myarticle');
try {
        $model->setId($id)->delete();
        echo "Data deleted successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

Monday, February 28, 2011

To add a tab in the right side of admin module form

To add a tab in the right side of admin module form

app\code\local\Namespace\module\Block\Adminhtml\module\Edit \Tabs.php
in function _beforeToHtml
copy paste the addTab code and change the name

Sunday, February 27, 2011

Magento export porduct as text file with txt extension for feed or feeds

Hey there

Check the code below for Magento export porduct as text file with txt extension for feed or feeds

Magento - Export & Import Custom Product Options

The code

<?php
    // Load Magento
    require_once $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
    umask(0);
    Mage::app();
   
    // set Store ID
    $storeId         = Mage::app()->getStore()->getStoreId();
   
    // set loop start timer
    $starttime         = microtime();
    $startarray     = explode(" ", $starttime);
    $starttime         = $startarray[1] + $startarray[0];
   
    // get basic configuration
    $baseUrl         = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
    $baseMediaUrl     = Mage::getSingleton('catalog/product_media_config')->getBaseMediaUrl();
    $storeCharset    = Mage::getStoreConfig('design/head/default_charset');
   
    // set report email sender
    $from_email        = Mage::getStoreConfig('trans_email/ident_general/email');    // sender: general contact email
    $from_name        = Mage::getStoreConfig('trans_email/ident_general/name');    // sender: general contact name
   
    // set report email recipient from backend user "admin"
    Mage::getSingleton('core/session', array('name' => 'adminhtml'));
    $admin             = Mage::getModel('admin/user')->load(1);                     // load first administrator
    $to_email        = $admin->getEmail();                                        // recipient: admin email
    $to_name        = $admin->getFirstname() . ' ' . $admin->getLastname();        // recipient: admin name
   
    // set Google Base feed filename and directory
    $_feed_dir        = '/media/feed/';                                            // Feed directory
    $feedDir         = $_SERVER['DOCUMENT_ROOT'] . $_feed_dir;                    // Path to feed directory
    $gbaseFeed        = 'google_base_feed.txt';                                    // Google base feed filename
    $tmpCounter        = 'counter.txt';                                            // Temporary counter file
    $timer            = 'timer.txt';                                                // Temporary timer file
   
    // set log filename and directory
    $logDir            = $_SERVER['DOCUMENT_ROOT'] . '/var/log/';                    // Log directory
    $logFile        = $logDir . date('Y-m') . '-gbase-feed.log';                // Google base log filename
   
    // define basic file constants
    define('SAVE_FEED_LOCATION',     $feedDir . $gbaseFeed);                        // google base file
    define('SAVE_FEED_RELOAD',         $feedDir . $tmpCounter);                    // counter file
    define('SAVE_FEED_TIMER',        $feedDir . $timer);                            // timer file
               
    // make sure we don't time out
    @ini_set('max_execution_time', '0');
    @ini_set('max_input_time', '0');
    @set_time_limit(0);
    @ignore_user_abort(true);
   
    // set headers to Magento character set
    header('Content-Type: text/html; charset=' . $storeCharset);
       
    try
    {
       
        // create FEED directory in case it doesn't exist yet
        if (!file_exists($feedDir))
        {
            mkdir($feedDir, 0777);
        }
       
        // basic setup
        $reload_line         = (file_exists(SAVE_FEED_RELOAD)) ? file_get_contents(SAVE_FEED_RELOAD) : 0;
        $timer_line         = (file_exists(SAVE_FEED_TIMER)) ? file_get_contents(SAVE_FEED_TIMER) : 0;
        $handle                = ($reload_line == 0) ? fopen(SAVE_FEED_LOCATION, 'w') : fopen(SAVE_FEED_LOCATION, 'a+');
        $handle_reload         = fopen(SAVE_FEED_RELOAD, 'w');
        $handle_timer         = fopen(SAVE_FEED_TIMER, 'w');
       
        if ($reload_line == 0)
        {
            $heading         = array('id','title','description','link','image_link','price','brand','product_type','condition', 'c:product_code');
            $feed_line        = implode("\t", $heading) . "\r\n";
            fwrite($handle, $feed_line);
        }
       
        //---------------------- GET THE PRODUCTS   
        $visibility         =     array (
                                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                                );
       
        $products = Mage::getModel('catalog/product')->getCollection();
        $products->addAttributeToFilter('status', 1);                     //enabled
        $products->addAttributeToFilter('visibility', $visibility);
        $products->addAttributeToSelect('sku');
        $prodIds = $products->getAllIds();
       
        foreach($prodIds as $productId)
        {
           
            if (($productId>=$reload_line) & ($productId<$reload_line+100))
            {
               
                // load product object
                $product                             = Mage::getModel('catalog/product');
                $product->load($productId);
               
                // populate product data array
                $product_data                         = array();   
                $product_data['sku']                = $product->getSku();   
                $product_data['title']                = $product->getName();
                $product_data['description']        = trim(ereg_replace("^[ \t\r\n]+|[ \t\r\n]+", " ", strip_tags($product->getShortDescription())));
                $product_data['link']                = $baseUrl . $product->getUrlKey() . Mage::getStoreConfig('catalog/seo/product_url_suffix') . '?source=googleps';
                $product_data['image_link']            = $baseMediaUrl . $product->getImage();
                $product_data['price']                = $product->getFinalPrice();
                $product_data['brand']                = $product->getAttributeText('manufacturer');   
                $product_data['product_type']         = '';
                $product_data['condition']            = 'new';
                $product_data['c:product_code']        = $product->getSku();
                   
                //get the product categories                   
                foreach($product->getCategoryIds() as $_categoryId)
                {
                    $category                         = Mage::getModel('catalog/category')->load($_categoryId);
                    $product_data['product_type']    .= $category->getName().', ';
                }
                $product_data['product_type']        = rtrim($product_data['product_type'],', ');       
   
                //sanitize data   
                foreach($product_data as $k=>$val)
                {
                    $bad                            = array('"',"\r\n","\n","\r","\t");
                    $good                            = array(""," "," "," ","");
                    $product_data[$k]                 = '"'.str_replace($bad,$good,$val).'"';
                }

                $feed_line                             = implode("\t", $product_data)."\r\n";
                fwrite($handle, $feed_line);
                fflush($handle);
                       
            }
        }

        //---------------------- WRITE THE FEED   
        fclose($handle);
        $feed_line_reload     = $reload_line + 100;
        fwrite($handle_reload, $feed_line_reload);
        fclose($handle_reload);
       
        // end of loop time
        $looptime             = microtime();
        $looparray             = explode(" ", $looptime);
        $looptime             = $looparray[1] + $looparray[0];
        $tmptime             = $looptime - $starttime;
       
        // sum of all passed loop times
        $feed_line_timer     = $timer_line + $tmptime;
        fwrite($handle_timer, $feed_line_timer);
        fclose($handle_timer);
    }
    catch(Exception $e)
    {
        //---------------------- LOG THE EXCEPTION   
        if (!file_exists($logDir))
        {
            mkdir($logDir, 0777);
        }
       
        if (!file_exists($logFile))
        {
            touch($logFile);
           
            $logHandle = fopen($logFile, 'w+');
           
            fwrite(              
                   $logHandle,
                   date('Y-m-d  H:i:s') . "  |  GOOGLE BASE FEED GENERATION PROBLEM\n\n" .
                   $e->getMessage() . "\n\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n"
            );
           
            fclose($logHandle);        
        }
        else
        {
           
            $ini_handle     = fopen($logFile, "r");
            $ini_contents     = fread($ini_handle, filesize($logFile));
            fclose($ini_handle);
           
            $logHandle         = fopen($logFile, 'w+');
            fwrite(
                   $logHandle,
                   date('Y-m-d  H:i:s') . "  |  GOOGLE BASE FEED PROBLEM\n\n" .
                   $e->getMessage() . "\n\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n" .
                   $ini_contents
            );
            fclose($logHandle);
           
        }
       
        //---------------------- SEND THE EXCEPTION    TO the ADMIN'S EMAIL
        $mail = new Zend_Mail($storeCharset);
        $mail->setBodyText($e->getMessage(), $storeCharset);
        $mail->setFrom($from_email, $from_name);
        $mail->addTo($to_email, $to_name);
        $mail->setSubject(date('Y-m-d') . ': Google base problem');
        try
        {
            $mail->send();
        }       
        catch(Exception $ex)
        {
            Mage::getSingleton('core/session')->addError('Cann\'t send the email. Try it later, please ...');
        }
       
        header('Content-Type: text/html; charset=' . $storeCharset);
        die($e->getMessage());
    }
    if (end($prodIds) < $reload_line)
    {
        // final feed generation time
        $totaltime         = round($feed_line_timer, 2); 
       
        // remove counter file
        @unlink(SAVE_FEED_RELOAD);
        @unlink(SAVE_FEED_TIMER);
       
        //---------------------- LOG THE SUCCESS   
        if (!file_exists($logDir))
        {
            mkdir($logDir, 0777);
        }
       
        if (!file_exists($logFile))
        {
            touch($logFile);
           
            $logHandle = fopen($logFile, 'w+');
           
            fwrite(              
                   $logHandle,
                   date('Y-m-d  H:i:s', filemtime ( SAVE_FEED_LOCATION ) ) . "  |  " . $gbaseFeed . "  |  " . count($prodIds) . " products exported  |  time: " . $totaltime . " seconds  |  size: " . format_bytes ( filesize ( SAVE_FEED_LOCATION ) ). "\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n"
            );
           
            fclose($logHandle);        
        }
        else
        {
           
            $ini_handle     = fopen($logFile, "r");
            $ini_contents     = fread($ini_handle, filesize($logFile));
            fclose($ini_handle);
           
            $logHandle         = fopen($logFile, 'w+');
            fwrite(
                   $logHandle,
                   date('Y-m-d  H:i:s', filemtime ( SAVE_FEED_LOCATION ) ) . "  |  " . $gbaseFeed . "  |  " . count($prodIds) . " products exported  |  time: " . $totaltime . " seconds  |  size: " . format_bytes ( filesize ( SAVE_FEED_LOCATION ) ). "\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n" .
                   $ini_contents
            );
            fclose($logHandle);
           
        }
       
        $log_handle     = fopen($logFile, "r");
        $log_contents     = fread($log_handle, filesize($logFile));
        fclose($log_handle);
       
        //---------------------- SEND THE LOG FILE TO ADMIN EVERY LAST DAY OF MONTH   
        if( date('d') == find_last_day(date('Y-m-d')) )
        {
           
            $mail = new Zend_Mail($storeCharset);
            $mail->setBodyText($log_contents, $storeCharset);
            $mail->setFrom($from_email, $from_name);
            $mail->addTo($to_email, $to_name);
            $mail->setSubject('Google base log from ' . date('m/Y') . ' period');
            try
            {
                $mail->send();
            }       
            catch(Exception $ex)
            {
                Mage::getSingleton('core/session')->addError('Cann\'t send the email. Try it later, please ...');
            }
           
        }
    }
    else
    {
        //---------------------- REFRESH SCRIPT TILL THE WHOLE FEED IS GENERATED
       
        curl_file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);

        // possible refresh variants

        //---------------------- script runs by web browser
        // header( 'refresh: 1; url=' . $_SERVER['PHP_SELF'] );
        // header('Location: '. $_SERVER['PHP_SELF']);
        // header("Location: http://$_SERVER[SERVER_NAME]" . substr($_SERVER["PHP_SELF"], 0, strrpos($_SERVER["PHP_SELF"], "/")) . "/");
        // echo '<META http-equiv="refresh" content="1; URL=' . $_SERVER['PHP_SELF'] . '">';
       
        //---------------------- script runs by cron
        // file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
        // curl_header_refresh('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
        // curl_file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
       
    }
   
    function format_bytes($bytes, $precision = 2)
    {
        $units                 = array('B', 'KB', 'MB', 'GB', 'TB');
        $bytes                 = max($bytes, 0);
        $pow                 = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow                 = min($pow, count($units) - 1);
        $bytes                 /= pow(1024, $pow);
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
   
    function find_last_day($anyDate)
    {
        //$anyDate            = '2009-08-25';                            // date format should be yyyy-mm-dd
        list($yr,$mn,$dt)    = split('-',$anyDate);                   
        $timeStamp            = mktime(0,0,0,$mn,1,$yr);               
        list($y,$m,$t)        = split('-',date('Y-m-t',$timeStamp));   
        $lastDayTimeStamp    = mktime(0,0,0,$m,$t,$y);               
        $lastDay            = date('d',$lastDayTimeStamp);           
        return $lastDay;
    }
   
    function curl_header_refresh($url)
    {
        $curl_init            = curl_init();
        curl_setopt($curl_init, CURLOPT_URL, $url);
        curl_setopt($curl_init, CURLOPT_HEADER, 0);
        $contents             = curl_exec($curl_init);
        curl_close($curl_init);
        return $contents;
    }
   
    function curl_file_get_contents($url)
    {
        $curl_init            = curl_init();                                            
        curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_init, CURLOPT_URL, $url);
        $contents             = curl_exec($curl_init);
        curl_close($curl_init);
        return $contents;
    }
   
?>


The Link
http://todd.be/notes/exporting-importing-magento-product-options
http://www.magentocommerce.com/boards/viewthread/153230/#t227283

Wednesday, February 23, 2011

Magento FConnect or magento facebook connect

Hear is the link for magento fconnect or magento facebook connect works gr8
smile
http://inchoo.net/ecommerce/magento/facebook-connect-magento-extension/

Php File upload for ckeditor 3.X

its good
http://download.cksource.com/CKFinder/CKFinder%20for%20PHP/2.0.2/ckfinder_php_2.0.2.zip

Magento insert update edit CRUD operations for dummies and beginers


Todo module for dummies: from the horse’s mouth :)

Some information  before we stare at the code:

Magento Path: phtmlàBlockàHelper->IndexControlleràphtml(updated)
Module naming: Modulename/Packagename e.g Shiva/Todo

Important  Folder info:

Adminhtml:contains config for admin menus like edit, grid, form, tab etc...

Block:contains front end outputs i.e the actions like getPostAction, editAction, prepareLayout etc..

Controllers:for interacting with the modules 

eg. indexcontroller : the action associated with the form like createAction, editAction, deleteAction

Adminhtml/XXXController : action for the backend like save edit,delete, massdelete etc... where XXX is your package name, here Todo

ETC contains the config directory
            config.xml default setting for module
            system.xml admininistration settings and admin form option ofr modules
Helper: helpers for module, covering areas such as translation e.g create, delete, edit functions are here Data.php

Model
Mysql4: (The top ORM model directory)---database related activity
 
Sql:mysql4-install-0.1.0.php contains database tables information required

Creating folder structure
To start with creating a Todo application in magento we need to build a module that becomes a part of the site that has its own URL. We will be creating our own module that will run on \todo URL structure.
Create the following folders in local directory [app\code\local\]
/Shiva
            /Todo
                        /Block
                        /etc
                        /Helper
/Model
/sql
/controllers
In etc/modules create Shiva_Todo.xml
etc/modules
- Shiva_Todo.xml
Tell magento that the new module is here
<?xml version="1.0"?>
<config>
    <modules>
        <Shiva_Todo>
            <active>true</active>
            <codePool>local</codePool>
        </Shiva_Todo>
    </modules>
</config>

Clear the cache and check in site->admin->system->Configuration->Advanced

Check if the module is “Enabled”.

For the frontend part

Your todo form is located in your theme
Path:-app\design\frontend\base_new\default\template\Todo\todo.phtml

Check the code in file
To view the formpage in address bar, check the form name front end by going to : Shiva/Todo/etc/config.xml and check the <frontend> tag

The form will be displayed as ‘todo’ as the name given in < frontName> tag

Some more file info…..

Helper class:

\Shiva\Todo\Helper

Helper:helpers for module, covering areas such as translation e.g create, delete, edit functions are here Data.php

Create a php file named Data.php

That file has a helper class named Shiva_Todo_Helper_Data in [Shiva/Todo/Helper/Data.php]

Check the code.

If you come across the code [‘todo/index/create’] it simply means in the todo module it has an Index controller and Create action [module / controller / action].

Check the necessary functions to get the id and perform respective actions for create, edit and delete.
Block class:
\Shiva\Todo\Block

Block: In Todo.php the class extend the template in the class and define the post Url actions
Grid.php
Location: \Adminhtml\Todo\Grid.php->define the display gird functions here

Edit.php
Location : \Adminhtml\Todo\ -> define the edit functions here
……..

Controllers:

IndexController.php
Location : \Shiva\Todo\controllers -> defines the actions here which are defined in Block and triggered from helper class
Admin side:
TodoController.php
Location : Shiva\Todo\controllers\Adminhtmlà for the admin actions like edit save etc….
Frontend part:
feedback.xml
Location: app\design\adminhtml\base_new\default\layout\Todo.xml
feedback.phtml
app\design\frontend\base_new\default\template\Todo\Todo.phtml
Do not forget to create a table name ‘todo’ in database
Form actions…………
To  create a record :
The flow

Magento Path: phtml-->Block-->Helper->IndexController-->phtml(updated)

Todo Path: todo.phtml---(on submit)--->(Todo.php)Block---$id-->Data.php)Helper->(indexcontroller.php)IndexController---redirect-->phtml(updated
)

Check the code in todo.phtml,Todo.php,Data.php,Indexcontroller.php
The screen shots:












Develop your custom module from the scratch with this demo and learn Magento
Download the source code here
The code shared is purely for education purpose only
# If you find any misleading info then tell us else tell others.