Tuesday, October 9, 2012

Import shopping cart price rule (coupon code)


<?php
$mageFilename = 'app/Mage.php';

require_once $mageFilename;

Varien_Profiler::enable();

Mage::setIsDeveloperMode(true);

ini_set('display_errors', 1);

umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);

class generateCouponCode{
   
    protected $_file = 'coupon_code.csv';
    protected $_count = 0;
   
    public function csvToArray($_file) {
        $csvArray = array();
        $file = fopen($_file, "r");
        fgetcsv($file);
        while (!feof($file)) {
            $values = fgetcsv($file);
            if ($values) {
                $csvArray[] = $values;
            }
        }
        return $csvArray;
    }

    public function getAllCustomerGroups() {
    //get all customer groups
        $customerGroups = Mage::getModel('customer/group')->getCollection();
        $groups = array();
        foreach ($customerGroups as $group) {
            $groups[] = $group->getId();
        }
        return $groups;
    }

    public function getAllWbsites() {
    //get all wabsites
        $websites = Mage::getModel('core/website')->getCollection();
        $websiteIds = array();
        foreach ($websites as $website) {
            $websiteIds[] = $website->getId();
        }
        return $websiteIds;
    }

    //read comments for each line
    public function generateRule($uniqueId) {

        $conditionProduct = Mage::getModel('salesrule/rule_condition_product')
                                                ->setType('salesrule/rule_condition_product')
                                                ->setAttribute('sku')
                                                ->setOperator('==')
                                                ->setValue('Bab0001');
                                               
        /** @var Mage_SalesRule_Model_Rule_Condition_Product_Found $conditionProductFound */
        $conditionProductFound = Mage::getModel('salesrule/rule_condition_product_found')
                                            ->setConditions(array($conditionProduct));
       
        /** @var Mage_SalesRule_Model_Rule_Condition_Combine $condition */
        $condition = Mage::getModel('salesrule/rule_condition_combine')
                    ->setConditions(array($conditionProductFound));
                   
        $rule = Mage::getModel('salesrule/rule');
        $rule->setName($uniqueId);
        $rule->setCouponType('2');
        $rule->setDescription('');
        $rule->setFromDate('2012-10-05');//date('Y-m-d')
        $rule->setToDate('2013-10-05');//date('Y-m-d')
        $rule->setCouponCode($uniqueId);
        $rule->setUsesPerCoupon(1); //number of allowed uses for this coupon
        $rule->setUsesPerCustomer(1); //number of allowed uses for this coupon for each customer
        $rule->setCustomerGroupIds($this->getAllCustomerGroups());
        $rule->setIsActive(1);
        $rule->setStopRulesProcessing(0); //set to 1 if you want all other rules after this to not be processed
        $rule->setIsRss(0); //set to 1 if you want this rule to be public in rss
        $rule->setIsAdvanced(1); //have no idea what it means :)
        $rule->setProductIds('');
        $rule->setSortOrder(0); // order in which the rules will be applied
        $rule->setSimpleAction('cart_fixed');
        $rule->setDiscountAmount('29.98');
        $rule->setDiscountQty(0); //Maximum Qty Discount is Applied to
        $rule->setDiscountStep(0); //used for buy_x_get_y; This is X
        $rule->setSimpleFreeShipping(0); //set to 1 for Free shipping
        $rule->setApplyToShipping(0); //set to 0 if you don't want the rule to be applied to shipping
        $rule->setWebsiteIds($this->getAllWbsites());
        $rule->setConditionsSerialized(serialize($condition->asArray()));
        $rule->setConditions($condition);
        $rule->loadPost($rule->getData());
       
        try
        {
            $rule->save();  
            Mage::log('Coupon code created for '.$uniqueId.'', null, 'couponcode.log');
            $this->_count++;
        }
        catch (Exception $e)
        {
            echo 'Caught exception for coupon code '.$uniqueId.':: ',  $e->getMessage(), "\n";
            Mage::log('Caught exception for coupon code '.$uniqueId.'::'.$e->getMessage().'', null, 'couponcode.log');
        }
    }
   
    public function importCsv() {
       
        $file = Mage::getBaseDir('base').DS.$this->_file;
       
        if (empty($file)) {
            throw new Exception("You need to upload a file to import.");
        }
       
        $csv = trim(file_get_contents($file));
       
        if (empty($csv)) {
            throw new Exception("The file is empty.");
        }
       
        $csv = $this->csvToArray($file);

        foreach ($csv as $key => $row) {
            $this->generateRule($row[0]);
        }
       
        echo sprintf("total %s coupon code created",$this->_count);
    }
   
}
$obj = new generateCouponCode();
$obj->importCsv();

?>

Wednesday, August 22, 2012

Backing Up The Database via SSH/Telnet

In order to back up your database via SSH or Telnet you will require 2 things:

1) SSH or Telnet access to your site. You will need to check with your hosting company to see if this is available.

2) An SSH/Telnet Client, such as PuTTy.

Open your SSH/Telnet client and log into your website. The command line prompt you will see will vary by OS.
For most hosting companies, this will bring you into the FTP root folder.

Type in the following to create a backup in the current directory:

mysqldump --opt -Q -u dbusername -p databasename > backupname.sql

Or to create a backup in a separate directory (signified by /path/to/) type:

mysqldump --opt -Q -u dbusername -p databasename > /path/to/backupname.sql

You will be prompted for the database password. Enter it and the database will backup.

If your hosting company has you on a remote MySQL server, such as mysql.yourhost.com, you will need to add the servername to the command line. The servername will be the same as in your config.php. The command line will be:

Current directory:

mysqldump --opt -Q -h servername -u dbusername -p databasename > backupname.sql

Separate directory:

mysqldump --opt -Q -h servername -u dbusername -p databasename > /path/to/backupname.sql

Thursday, August 16, 2012

PHP: Get all tables from database


<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

Magento: Get admin user’s data (id, name, username, email, password, etc).


$userArray = Mage::getSingleton('admin/session')->getData();

$user = Mage::getSingleton('admin/session');
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();

Magento: Update layout or add js with controller



public function myAction()
{

    /* ... Some code ...*/

    $update = $this->getLayout()->getUpdate();

    /* ... Some code ...*/

    $this->addActionLayoutHandles();

    /* ... Some code ...*/

    $this->loadLayoutUpdates();

    /* ... Some code ...*/

    $update->addUpdate('
        <reference name="head">
            <action method="addJs"><script>varien/product.js</script></action>
            <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params /><!--<if/><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if /><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if /><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>skin_js</type><name>js/bundle.js</name></action>
        </reference>
    ');

    /* ... Some code ...*/

    $this->generateLayoutXml()->generateLayoutBlocks();

    /* ... Some code ...*/

    $this->renderLayout();

}


Wednesday, August 15, 2012

Magento: Admin page not found error

After moving magento to live server or demo server. If not able to access admin page or got page not found error. apply below sql query.

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

Monday, July 30, 2012

Upgrading magento from 1.4.1.1 to 1.6.0.0 (issue with upgrading databse)

If found issue with query "ALTER TABLE `sales_flat_order` ADD UNIQUE `UNQ_INCREMENT_ID` ( `increment_id` )" and taking a long time at this stage than need to find duplicate entires..

try this...

find duplicate increment ids..
SELECT increment_id, COUNT(*) c FROM sales_flat_order GROUP BY increment_id HAVING c > 1;

create new file on root and run below code..

require 'app/Mage.php';
Mage::app('admin');

 $dupes= array('R00168293-1','R00168534-1','R00168946-1');

Mage::getSingleton("core/session", array("name" => "adminhtml"));
Mage::register('isSecureArea',true);
$collection = Mage::getResourceModel('sales/order_collection')
  ->addAttributeToSelect('*')
  ->setPageSize(5000)
  ->addFieldToFilter('status', 'canceled')
  ->addFieldToFilter('increment_id', array('in'=>$dupes))
  ->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
  try {
    $col->delete();
  } catch (Exception $e) {
    throw $e;
  }
}

Wednesday, July 25, 2012

Useful git commands

Setup 

git clone url

Clone a repository specified by url. This is similar to “checkout” in some other version control systems such as Subversion and CVS.
git init
Create an new git repository in the current directory or reinitialize an existing one.
git init --bare
Create an new git repository in the current directory without an associated working tree. This is useful for repositories that serve as mirrors.
git update-server-info
Allow a git repository to act as a dumb server (for remote access).

Adding/Deleting

git add file1 file2 ...
Add file1, file2, etc. to the project.
git add dir
Add all files under directory dir to the project, including subdirectories.
git add .
Add all files under the current directory to the project, including subdirectories.
git rm file1 file2 ...
Remove file1, file2, etc. from the project (and the filesystem).

Commiting

git commit file1 file2 ... [-m msg]
Commit changes in file1, file2, etc., optionally using commit message msg or otherwise opening editor for commit message entry.
git commit -a [-m msg]
Commit changes made to all tracked files since the last commit, optionally using commit message msg or otherwise opening editor for commit message entry.
git commit --amend file1 file2 ... [-m msg]
Re-commit previous commit, including file1, file2, etc., using previous commit message or, optionally, a new one given by msg.

Sharing

git push [remote]
Update the remote repository named remote with commits across all branches that are common between your local repository and remote. If remote is not specified, but a remote named “origin” is defined, then remote defaults to “origin”. Local branches that were never pushed to the server in the first place are not shared.
git push remote branch
Update the remote repository named remote (e.g. “origin”) with commits made to branch since the last push. This is always required for new local branches (including “master” in a new repository). After the first explicit push, “git push” by itself is sufficient.
git pull remote
Update the current branch with changes from the remote named remote (defaults to “origin” if not given). Note that for this to work, “.git/config” must define merge configuration variables for the current branch.

Information

Changes and Differences

git status
Show files added to the index, files with changes, and untracked files.
git diff
Show unstaged changes made since your last commit.
git diff --cached
Show changes staged for commit (i.e., difference between index and last commit).
git diff HEAD
Show changes (staged and unstaged) in working directory since last commit.
git diff rev [path(s)]
Show differences between working directory and revision rev, optionally limiting comparison to files found in one or more space-separated file paths or subdirectories given by path(s).
git diff rev1..rev2 [path(s)]
Show differences between two revisions, rev1 and rev2, optionally limiting comparison to files found in one or more space-separated file paths or subdirectories given by path(s).
git diff rev1...rev2 [path(s)]
Show differences between the last common ancestor of two revisions, rev1 and rev2, optionally limiting comparison to files found in one or more space-separated file paths or subdirectories given by path(s).

File and Directory Contents

git show rev:file
Show contents of file (specified relative to the project root) from revision rev.
git ls-files [-t]
Show all tracked files (“-t” shows file status).
git ls-files --others
Show all untracked files.

Commit History

git log
Show recent commits, most recent on top.
git log [path(s)]
Show recent commits, most recent on top, limited to the file or files found on path(s) if given.
git log -p
Show recent commits, most recent on top, with full diffs.
git log -p [path(s)]
Show recent commits, most recent on top, with full diffs, limited to files found in one or more space-separated file paths or subdirectories given by path(s).
git log -g
Show recent commits, most recent on top, walking the full reflog entries instead of the commit ancestry chain up to the current HEAD. By default, “git log” reports all commits only up to the current HEAD, even if HEAD has descendents on the current branch (as, for example, might happen if you ran “git reset rev” to move HEAD to a previous point in history). The “-g” option will report the full history.
git log --stat [path(s)]
Show recent commits, with stats (files changed, insertions, and deletions), optionally limited to files found in one or more space-separated file paths or subdirectories given by path(s).
git log --author=author
Show recent commits, only by author.
git log --after="MMM DD YYYY"
Show commits that occur after a certain date, e.g. “Jun 20 2008″.
git log --before="MMM DD YYYY"
Show commits that occur before a certain date.
git whatchanged file
Show only the commits which affected file listing the most recent first.
git blame file
Show who authored each line in file.
git blame file rev
Show who authored each line in file as of rev (allows blame to go back in time).
git rev-list --all
List all commits.
git rev-list rev1..rev2
List all commits between rev1 and rev2.
git show rev
Show the changeset (diff) of a commit specified by rev.
git show rev -- path(s)
Show the changeset (diff) of a commit rev , optionally limited to files found in one or more space-separated file paths or subdirectories given by path(s).

Searching

Searching for Content

git grep regexp
Search working tree for text matching regular expression regexp.
git grep -e regexp1 [--or] -e regexp2
Search working tree for lines of text matching regular expression regexp1 or regexp2.
git grep -e regexp1 --and -e regexp2
Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only.
git grep -l --all-match -e regexp1 -e regexp2
Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2.
git grep regexp $(git rev-list --all)
Search all revisions for text matching regular expression regexp.
git grep regexp $(git rev-list rev1..rev2)
Search all revisions between rev1 and rev2 for text matching regular expression regexp.

Searching Logs and Commit History

git log --grep regexp
Search commit logs for lines of text matching regular expression regexp.
git log --grep regexp1 --grep regexp2
Search commit logs for lines of text matching regular expression regexp1 or regexp2.
git log --grep regexp1 --and --grep regexp2
Search commit logs for lines of text matching regular expression regexp1 and regexp2.

Branching

Listing Branches

git branch
List all local branches.
git branch -r
List all local and remote branches.

Creating Branches

git branch new-branch
Create a new branch named new-branch, based on current branch.
git branch new-branch rev
Create a new branch named new-branch, based on revision specified by tree-ish rev.
git branch --track new-branch remote/remote-branch
Create a new tracking branch named new-branch, referencing, and pushing/pulling from, the branch named remote-branch on remote repository named remote.

Checking Out Branches/Revisions

git checkout branch
Switch to branch named branch. This updates the working tree to reflect the state of the branch named branch, and sets HEAD to “.git/refs/heads/branch”.
git checkout rev
Switch to revision specified by tree-ish rev, without explicitly branching. Running “git checkout -b new-branch” will create a branch from the checked out version.

Simultaneous Creating and Switching Branches

git checkout -b new-branch
Create a new branch named new-branch, referencing the current branch, and check it out.
git checkout -b new-branch rev
Create a new branch named new-branch based on the tree-ish rev, update the working tree to reflect its state, and check it out (switch to it).

Deleting Branches

git branch -d branch
Delete the local branch named branch (fails if branch is not reachable from the current branch).
git branch -D branch
Force delete of the local branch named branch (works even if branch is not reachable from the current branch).
git branch -d -r remote/branch
Delete a “local remote” branch, i.e. a local tracking branch.
git push remote :heads/branch
Delete a branch named branch from a remote repository.

Merging

In all of the following, a merge strategy can be specified by the “-s strategy” argument, which can be one of: “resolve”, “recursive”, “octopus”, “ours”, or “subtree”. If you tried a merge which resulted in a complex conflicts and would want to start over, you can recover with “git reset –hard”. If you accidently merged and want to unmerge, you can “git reset –hard ORIG_HEAD”.
git merge branch
Merge branch branch into the current branch and commit the result. This command is idempotent and can be run as many times as needed to keep the current branch up-to-date with changes in branch.
git merge branch --no-commit
Merge branch branch into the current branch, but do not autocommit the result. Allows for inspection or tweaking of the merge result before committing.
git merge branch --squash --commit
Merge branch branch into the current branch as a single commit.

Undoing

Reverting is different from resetting in that reverts usually create new history while resets usually remove existing history. The changes of a revert are applied to the current state of the repository, and, if committed, results in a new repository state descending from the current one. Reverts are safe to publish even if they revert a previously published commit, and, in fact, are the correct way of dealing with the undoing of published commits. Resetting, on the other hand, represents (a possibly selective) “rewind” to a previous state in the history “starting again” from there. Resets should never be committed if they undo commits that have been published or pushed to remote repositories, as this would result in invalid object histories and commit ID’s in the remote repositories.

Reverting

git revert rev
Revert the changes introduced by rev, and record a new commit that records it. This does not do the same thing as similarly named commands in other VCS’s such as “svn revert” or “bzr revert”.
git checkout path(s)
Re-checkout file or files specified by path(s), overwriting any local changes. This is most similar to “svn revert”.
git checkout -- path(s)
As above, but use this syntax if you have a branch or tag with the same name as a path given in path(s).
git checkout rev path(s)
Re-checkout file or files specified by path(s) to version specified by rev (which may be specified using a SHA1 commit ID, branch name, or tag), overwriting any local changes.
git checkout -f
Throw away all local changes since last commit, restoring working tree to last committed state (plus untracked files) and clearing index. Unlike “git reset –hard”, does not move HEAD, and so will not, for example, cleanly forget about a failed merged: use “git reset –hard” for this.

Resetting

git reset
Resets the index (i.e., removes all changes staged for commit) but does not modify the working tree (i.e., the changes in the files are preserved), and does not change HEAD.
git reset rev -- path(s)
Restores file or files specified by path(s) to revision specified by rev, without changing HEAD.
git reset rev
Sets the current HEAD to the commit specified by rev (which may be specified using a SHA1 commit ID, branch name, or tag), and resets the index but not the working tree (i.e current changes in the working tree are preserved).
git reset --soft rev
Sets the current HEAD to the commit specified by rev, and does not modify the working tree, but keeps changes in the index for editing. For example, if something was forgotten or omitted in the previous commit, “git reset –soft HEAD^” will undo the last commit, and keep all changes in the index for editing and the next commit.
git reset --hard
Throw away all local changes since last commit, restoring working tree to last committed state (plus untracked files) and resetting both index and HEAD.
git reset --hard rev
Sets the current HEAD to the commit specified by rev, and changes the working tree to mirror the new HEAD (plus untracked files). For example, “git reset –hard ORIG_HEAD” will undo the most recent successful merge and any changes that occurred after. Useful for forgetting about the merge just done. If there are conflicts (the merge was not successful), use “git reset –hard” instead.

Stashing

Use “git stash” when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.
git stash save [msg]
Save your local modifications to a new stash, and run “git reset –hard” to revert them. This is the default action when no subcommand is given. If msg is not explicitly given, then it defaults to “WIP on branch” where “branch” is the current branch name.
git stash list
List all current stashes.
git stash apply [stash]
Restore the changes recorded in the stash on top of the current working tree state. When no stash is given, applies the latest one (stash@{0}). The working directory must match the index.
git stash pop [stash]
Remove a single stashed state from the stash list and apply on top of the current working tree state. When no stash is given, the latest one (stash@{0}) is assumed.
git stash clear
Remove all the stashed states.
git stash drop [stash]
Remove a single stashed state from the stash list. When no stash is given, it removes the latest one. i.e. stash@{0}.
git stash branch new-branch [stash]
Creates and checks out a new branch named new-branch starting from the commit at which the stash was originally created, applies the changes recorded in stash to the new working tree and index, then drops the stash if that completes successfully. When no stash is given, applies the latest one.

Cleaning

git clean -f
Remove all untracked files from working copy.
git clean -fd
Remove all untracked files and directories from working copy.
git clean -fX
Remove all ignored files from working copy.
git clean -fXd
Remove all ignored files and directories from working copy.
git clean -fx
Remove all untracked and ignored files from working copy.
git clean -fxd
Remove all untracked and ignored files and directories from working copy.

Remotes

git remote add remote url
Adds a remote named remote for the repository at url.
git rm remote url
Remove reference to remote repository named remote: all tracking branches and configuration settings for remote are removed.
git push remote :heads/branch
Delete the branch branch from the remote repository named remote.
git remote prune remote
Prune deleted remote branches from git branch listing. These branches have already been removed from the remote repository named remote, but are still locally available in “remotes/remote”.

Plumbing

test sha1-A = $(git merge-base sha1-B)
Determine if merging sha1-B into sha1-A is achievable as a fast forward; non-zero exit status is false.

Configuration

You can add “--global” after “git config” to any of these commands to make it apply to all git repositories (writes to ~/.gitconfig).
git config user.email author@email.com
Set email for commit messages.
git config user.name 'author name'
Set name for commit messages.
git config branch.autosetupmerge true
Tells git-branch and git-checkout to setup new branches so that git-pull(1) will appropriately merge from that remote branch. Recommended. Without this, you will have to add “--track” to your branch command or manually merge remote tracking branches with “fetch” and then “merge“.

Environment Variables

GIT_AUTHOR_NAME, GIT_COMMITTER_NAME
Full name to be recorded in any newly created commits. Overrides user.name in .git/config.
GIT_AUTHOR_EMAIL, GIT_COMMITTER_EMAIL
Email address to be recorded in any newly created commits. Overrides user.email in .git/config

Monday, July 23, 2012

Remove index.php from url in magento

1) Login to admin section by using the URL
http://domain.com/index.php/admin
2) then go to “System >>  Configuration >>Web >> Search Engines Optimization”
Use Web Server Rewrites : YES
3) Go to “System >>  Configuration >>Web >>Secure”
Use secure URL Frontend: YES
4)Then create the .htaccess file under your the magento installed folder.
If the magento installed under document root ( /home/username/public_html) then add follogig rules into .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

and If the magento installed under /shop or directory then add the following rules into ” /home/username/public_html/shop/.htaccess ” file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /shop/index.php [L]
</IfModule>

Monday, July 16, 2012

Creating Product And Category Attributes By Script

// product attribute

$installer->addAttribute('catalog_product', 'test',
    array(
    'attribute_set'     => 'Default',
    'group'             => 'General',
    'type' => 'int',
    'input' => 'select',
    'label' => 'Test',
    'source' => 'eav/entity_attribute_source_table',
    'required' => false,
    'visible'           => true,
    'user_defined' => true,
    'unique' => false,
    'used_for_sort_by' => false,
    'searchable'        => true,
    'filterable'        => true,
    'is_filterable_in_search' => true,
    'used_in_product_listing' => true,
    'default' => false,
    'global'        =>  Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
            'option'            => array (
                                   'value' => array(
                                            'optionone'            =>array(0=>'option1'),
                                            'optiontwo'            =>array(0=>'option2'),
                                            'optionthree'        =>array(0=>'option3'),
                                            'optionfour'        =>array(0=>'option4'),
                                            )
                               ),
    'configurable'        => true
   )
);

$installer->addAttribute('catalog_product', 'test',
    array(
    'attribute_set'     => 'Default',
    'group'             => 'General',
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Test',
    'source' => '',
    'required' => false,
    'user_defined' => true,
    'visible_on_front'           => false,  
    'visible'           => true,
    'unique' => false,
    'used_in_product_listing' => false,
    'default' => false,
    'global'        =>  Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL
   )
);


//Category Attributes
//type image

$installer->addAttribute('catalog_category', 'image', array(
    'group'         => 'General',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Image',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));





Set Product Data In Magento Version <= 1.5

It is required to set current store for saving data.


Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = new Mage_Catalog_Model_Product();
$product->setData($data);
$product->save();

X-Cart Add Pinit Button On Product Detail Page

x cart pin it button

{assign var="url" value="`$current_location`/`$canonical_url`"} OR
{assign var="url" value="`$current_location`/product.php?productid=`$product.productid`"}
OR
{assign var="url" value="`$current_location`/`$product.clean_url`.html"}

Not sure which one will work for you

<a href="http://pinterest.com/pin/create/button/?url={$url}&media={$product.image_url}&description ={$product.descr}" class="pin-it-button" count-layout="horizontal">Pin It</a>

Mobile User Agent For Add Exception Magento

Mobile user agents

iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini

Edit Footer Toolbar On Product List Page

Create new file like footertoolbar.phtml or by any other name. modify by your requirements.

Called in list page using

<catalog_category_default>
        <reference name="product_list">
            <block type="catalog/product_list_toolbar" name="listfooter" template="catalog/product/list/footertoolbar.phtml">
                <block type="page/html_pager" name="product_list_toolbar_pager"/>
            </block>
        </reference>
 </catalog_category_default>

and in list.php file get set collection and get child html

<?php $this->getChild('listfooter')->setCollection($this->getLoadedProductCollection()); ?>
<?php echo $this->getChildHtml('listfooter') ?>

Mage_Adminhtml_Block_Widget_Form

Mage_Adminhtml_Block_Widget_Form class is never instantiated.
It is only extended by other classes.
This is never called inside Magento ‘new Mage_Adminhtml_Block_Widget_Form()’.
So even if you override the class all the other classes that extend Mage_Adminhtml_Block_Widget_Form will still extend the original one and not your class.
You are not adding an other level in the inheritance tree. You just add and other sibling to the classes that extend Mage_Adminhtml_Block_Widget_Form.

You have 2 solutions here.
1. Quick and dirty - copy the Mage_Adminhtml_Block_Widget_Form class file in the app/code/local folder (following all the required paths) and edit it in there. When Magento looks for a class first searches in the app/code/local folder then in app/code/community and in the end in app/code/local. This means that all the classes that extend Mage_Adminhtml_Block_Widget_Form will extend your class instead (because this is the first one found by Magento).

2. Clean but very time consuming method (that might turn out to be useless in the end) - Create a class that extends Mage_Adminhtml_Block_Widget_Form (just like you did) and override all the classes that extend Mage_Adminhtml_Block_Widget_Form and make them extend your class. This is a good practice if you have a small number of classes in this case (for example it could work for Mage_Customer_Model_Address_Abstract) but in your case there are a lot of these classes. It will take a lot of time and might be hard to manage in the end.

So you can use first solution.  There is a risk that on a future upgrade you will loose some functionality (but the chance is slim). You might loose more (time and functionality with the second one).

Saturday, July 14, 2012

Hide Pager And Filter Visibility In Admin Grid

$this->setSortable(false);
$this->setPagerVisibility(false);
$this->setFilterVisibility(false);

Friday, July 13, 2012

Interesting facts about Magento Enterprise

  • Magento's Community version has been downloaded over 1 million since March 2008
  • Over 25,000 Web stores with over $25 billion in online revenue have been generated by Magento-engined stores -- second only to eBay
  • An open source platform, Magento counts with over 50,000 developers on forum
  • 60,000+ merchants on Magento
  • 180+ Solution Providers selling Magento Worldwide  
  • Over 5000 downloads a day of community product 

Magento Javascript Validation Classes


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

Please 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-zip-international

Please enter a valid zip code

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