Magento 2 - tips and tricks every Developer should know

Magento 2 has a reputation for being complicated, and honestly that reputation is earned. The learning curve is steep, the documentation has gaps, and some of its architectural decisions only make sense once you have been burned by the alternative. I have been working with Magento 2 since its early releases and the tips in this post come directly from real projects, real mistakes, and things I wish someone had told me before I spent hours figuring them out the hard way.

This is not a list of things you will find in the official documentation. These are the practical things that make daily Magento 2 development faster, less frustrating, and more maintainable.

Development Workflow Tips

1. Always work in developer mode during development

This sounds obvious but I have seen teams develop in default mode and wonder why their template changes are not showing up. In developer mode, Magento disables most caching, enables full error reporting, and processes frontend assets on the fly. Switch modes from the command line:

php bin/magento deploy:mode:set developer

The flip side is that production mode compiles and minifies everything, which is why you must run the full deployment commands before pushing to production. Never deploy to production in developer mode. It is slower and exposes internal errors to visitors.

2. Know your cache types and clear only what you need

Running php bin/magento cache:flush clears everything and takes time. In most cases during development you only need to clear specific cache types. Clearing just the config cache after a config change, or just the layout cache after a layout XML change, is significantly faster.

# Clear only config cache
php bin/magento cache:clean config

# Clear layout and block cache after layout changes
php bin/magento cache:clean layout block_html

# Clear full page cache after template changes
php bin/magento cache:clean full_page

# See all cache types and their status
php bin/magento cache:status

Learn which cache type corresponds to which kind of change. It will save you minutes every time you test something.

3. Use n98-magerun2 for everything the CLI does not cover

n98-magerun2 is the Swiss Army knife for Magento 2 development. It extends Magento's CLI with hundreds of useful commands for database management, admin user creation, module management, and much more.

# Install globally
composer global require n98/magerun2

# Create an admin user without going through the UI
n98-magerun2 admin:user:create --username=devadmin --email=dev@example.com \
    --password=Dev@12345 --firstname=Dev --lastname=Admin

# Run a database query directly
n98-magerun2 db:query "SELECT * FROM admin_user"

# Open a MySQL console connected to Magento's database
n98-magerun2 db:console

# Show all configuration values for a path
n98-magerun2 config:store:get catalog/search/*

The db:console command alone is worth installing it for. No more hunting for database credentials in env.php every time you need to run a query.

4. Setup Xdebug properly

Too many Magento developers rely on var_dump and log files for debugging. Xdebug with step-through debugging changes how you work entirely. You can inspect the full call stack, watch variable values change in real time, and understand exactly what Magento is doing at any point in its request cycle.

The most common Xdebug configuration issue with Magento is the request timeout. Set a generous timeout in your php.ini because Magento's bootstrap takes longer than a typical PHP application and Xdebug adds overhead:

xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host=host.docker.internal  ; if using Docker
xdebug.client_port=9003
xdebug.max_execution_time=0  ; disable timeout during debug sessions

5. Use the Magento 2 console to run cron manually

Waiting for Magento's cron to run on its schedule during development is painful. You can trigger specific cron groups manually:

# Run all cron jobs
php bin/magento cron:run

# Run a specific cron group
php bin/magento cron:run --group=index

# Check cron schedule
php bin/magento cron:schedule

If something is not updating after you expect it to, a manual cron run is often the answer.

Performance Tips

6. Enable Redis for Cache and Session Storage

File-based cache storage is fine for development but it will not scale in production. Redis handles Magento's cache and session storage significantly better, especially under concurrent load. Configure it in app/etc/env.php:

'cache' => [
    'frontend' => [
        'default' => [
            'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
            'backend_options' => [
                'server'   => '127.0.0.1',
                'port'     => '6379',
                'database' => '0',
                'password' => '',
            ],
        ],
        'page_cache' => [
            'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
            'backend_options' => [
                'server'   => '127.0.0.1',
                'port'     => '6379',
                'database' => '1',  // separate database for full page cache
            ],
        ],
    ],
],
'session' => [
    'save'         => 'redis',
    'redis' => [
        'host'     => '127.0.0.1',
        'port'     => '6379',
        'database' => '2',
    ],
],

Use a separate Redis database number for each type. Mixing the page cache and session data in the same database means a cache flush will wipe active sessions, which logs out all your customers. Learned that one the hard way on a live site.

7. Flat Catalog tables speed up large catalogues

By default Magento stores product and category attributes using the EAV (Entity-Attribute-Value) model. For catalogues with thousands of products and many attributes, this means dozens of JOIN operations per product list query. Flat tables consolidate all attributes into a single table per entity type, which is dramatically faster for reads.

# Enable flat catalog in admin: Stores > Configuration > Catalog > Catalog
# Then rebuild the flat tables
php bin/magento indexer:reindex catalog_category_flat
php bin/magento indexer:reindex catalog_product_flat

The tradeoff is that the flat tables need to be kept in sync with the EAV tables, which adds a small overhead to product saves. For read-heavy stores with large catalogues this is almost always worth it.

8. Optimise your indexers and set them to update on schedule

Magento has multiple indexers that rebuild data structures when products, categories, or prices change. Running them on "Update on Save" means every product edit triggers a full or partial reindex, which blocks the save operation and slows down the admin. On stores with large catalogues this can make product editing painfully slow.

# Set all indexers to update on schedule
php bin/magento indexer:set-mode schedule

# Or set a specific indexer
php bin/magento indexer:set-mode schedule catalogrule_rule

# Check current indexer status
php bin/magento indexer:status

With schedule mode, reindexing happens on cron runs rather than during save operations. Editors get fast saves, the index stays reasonably fresh, and you avoid timeout issues when making bulk changes.

9. Enable Varnish for full page cache in production

Magento's built-in full page cache is decent but Varnish is significantly faster for high-traffic stores. Magento generates a Varnish configuration file for you:

php bin/magento varnish:vcl:generate --export-version=6 > /etc/varnish/default.vcl

Set the caching application to Varnish in the admin under Stores, Configuration, Advanced, System, Full Page Cache. One thing that catches developers out: after enabling Varnish you need to set the HTTP port to 80 and let Varnish handle requests on that port, with Magento behind it on a different port. Your web server config needs to reflect this or you will get redirect loops.

10. Use Asynchronous and deferred indexing for imports

If you run regular product imports via CSV or API, synchronous indexing after each import will slow things to a crawl. Enable asynchronous reindexing and let the cron handle it:

# Enable async grid indexing
php bin/magento config:set dev/grid/async_indexing 1

For bulk imports using the Import API, make sure you call php bin/magento indexer:reindex after the import completes rather than relying on the save events to trigger reindexing. Batch imports at the end, not during.

Backend and Admin Tips

11. Customise Admin Grids Without Rewriting the Whole Grid

One of the most common admin customisations is adding a column to an existing grid, like the orders grid or the customers grid. The wrong way is to override the entire grid PHP class. The right way is to use a UI Component XML file to extend just what you need.

Create a layout XML file in your module at view/adminhtml/layout/sales_order_grid.xml:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="sales_order_grid">
            <arguments>
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="update_url" xsi:type="url" path="mui/index/render"/>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Then extend the UI component definition in view/adminhtml/ui_component/sales_order_grid.xml to add your column. This approach survives Magento upgrades far better than class overrides because you are extending, not replacing.

12. Use Virtual types to avoid unnecessary classes

Virtual types are one of Magento's most underused features. They let you create a variation of an existing class with different constructor arguments, without writing a new PHP file. This is useful when you need multiple instances of the same class configured differently.

<!-- di.xml -->
<virtualType name="Vendor\Module\Model\CustomLogger"
             type="Magento\Framework\Logger\Monolog">
    <arguments>
        <argument name="name" xsi:type="string">customModule</argument>
        <argument name="handlers" xsi:type="array">
            <item name="system" xsi:type="object">
                Vendor\Module\Logger\Handler\Custom
            </item>
        </argument>
    </arguments>
</virtualType>

<!-- Use the virtual type as a dependency -->
<type name="Vendor\Module\Model\SomeService">
    <arguments>
        <argument name="logger" xsi:type="object">
            Vendor\Module\Model\CustomLogger
        </argument>
    </arguments>
</type>

This creates a logger instance with custom configuration without writing a new Logger class. Clean, upgrade-safe, and takes five minutes once you understand the pattern.

13. Use Plugins (Interceptors) Instead of Rewrites

Magento 1 developers often reach for class rewrites out of habit. In Magento 2, plugins are almost always the better choice. Plugins let you execute code before, after, or around a public method of any class without replacing the entire class.

<!-- di.xml -->
<type name="Magento\Catalog\Model\Product">
    <plugin name="vendor_module_product_plugin"
            type="Vendor\Module\Plugin\ProductPlugin"
            sortOrder="10"
            disabled="false"/>
</type>
<?php

namespace Vendor\Module\Plugin;

use Magento\Catalog\Model\Product;

class ProductPlugin
{
    // Runs after getName() and can modify the return value
    public function afterGetName(Product $subject, string $result): string
    {
        if ($subject->getTypeId() === 'bundle') {
            return $result . ' (Bundle)';
        }

        return $result;
    }

    // Runs before setPrice() and can modify the arguments
    public function beforeSetPrice(Product $subject, float $price): array
    {
        // Ensure price is never negative
        return [max(0, $price)];
    }
}

Multiple plugins can target the same method and the sortOrder attribute controls execution order. This means your customisation coexists with other modules' plugins rather than one rewrite blocking another entirely.

14. Log to custom files, not the default system log

Everything in Magento logs to var/log/system.log by default. On an active store this file grows fast and becomes almost useless for finding specific module issues. Create a custom logger for your module that writes to its own file:

<?php

namespace Vendor\Module\Logger;

use Monolog\Logger;

class Handler extends \Magento\Framework\Logger\Handler\Base
{
    protected $loggerType = Logger::DEBUG;
    protected $fileName   = '/var/log/vendor_module.log';
}

Register this handler in your module's di.xml using a virtual type (see tip 12 above) and inject it wherever you need logging. Your module's debug output goes to its own file and does not get buried in the system log noise.

Frontend and Theming Tips

15. Extend Parent Themes Rather Than Modifying Them Directly

Never modify Luma or Blank theme files directly. Magento updates will overwrite your changes and you will have no way of knowing what was changed. Always create a child theme that declares the parent:

<!-- app/design/frontend/Vendor/mytheme/theme.xml -->
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>Vendor My Theme</title>
    <parent>Magento/luma</parent>
</theme>

To override a template, copy it from the parent theme into the same relative path in your theme and edit the copy. Magento's theme fallback system will use your version. To override a layout, create a layout XML file with the same name in your theme's layout directory and add only the changes you need.

16. Use the less variable override system properly

Magento 2 uses Less for stylesheets and has a variable system that lets you customise colours, fonts, and spacing without touching the source Less files. Override variables in your theme by creating web/css/source/_variables.less:

// Override the primary colour across the entire theme
@color-orange: #e84040;

// Change the default font
@font-family__base: 'Inter', sans-serif;
@font-family__serif: Georgia, serif;

// Button styling
@button__background: @color-orange;
@button__border-radius: 4px;

// Navigation
@navigation__background: #1a1a2e;
@navigation-level0-item__color: #ffffff;

This propagates through Magento's entire Less stack without you touching a single source file. Most visual customisations can be done entirely through variable overrides. Only write custom Less for things the variable system does not cover.

17. Understand static content deployment

The most common frontend issue I see in production deployments is forgetting to deploy static content, or deploying it for the wrong locales.

# Deploy for all themes and locales
php bin/magento setup:static-content:deploy

# Deploy for specific locales only (faster)
php bin/magento setup:static-content:deploy en_US en_GB

# Deploy a specific theme
php bin/magento setup:static-content:deploy -t Vendor/mytheme en_US

# Use parallel deployment for speed on large stores
php bin/magento setup:static-content:deploy --jobs=4 en_US

If your static content looks correct in developer mode but breaks in production, you almost certainly have a deployment issue. Check that all your locales are included in the deploy command and that the deployment ran successfully after the last code change.

18. Use RequireJS config to load JavaScript properly

Adding JavaScript in Magento 2 is not as simple as dropping a script tag in a template. The right way is through RequireJS, which manages dependencies and load order. Define your JavaScript modules in view/frontend/requirejs-config.js:

var config = {
    map: {
        '*': {
            'customSlider': 'Vendor_Module/js/custom-slider',
        }
    },
    shim: {
        'customSlider': {
            deps: ['jquery'],
        }
    },
    paths: {
        'slick': 'Vendor_Module/js/vendor/slick.min',
    }
};

Then use it in a template or another JavaScript file:

require(['customSlider', 'jquery'], function(CustomSlider, $) {
    var slider = new CustomSlider({
        element: $('.product-gallery'),
        autoplay: true,
    });
});

The RequireJS approach means your JavaScript is only loaded when needed, dependencies are guaranteed to be available, and your code does not conflict with other modules' JavaScript.

Common Mistakes to avoid

19. Do Not use ObjectManager directly in your code

You will see ObjectManager used in old tutorials and even in some core Magento code. Do not follow that pattern in your own modules. Using ObjectManager directly bypasses dependency injection, makes code untestable, and creates hidden dependencies.

<?php

// Wrong. Do not do this.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);

// Right. Inject dependencies through the constructor.
class MyService
{
    public function __construct(
        private \Magento\Catalog\Model\ProductFactory $productFactory
    ) {}

    public function doSomething(): void
    {
        $product = $this->productFactory->create();
    }
}

The only acceptable place to use ObjectManager directly is in factory classes and proxy classes, and even there Magento generates those automatically through its code generation system.

20. Do Not modify core files

Every Magento update will overwrite your changes. Use plugins, preferences, layout overrides, and template overrides instead. If you find yourself editing a file in vendor/magento/, stop and find the proper extension point instead. There is always one.

21. Run Code egneration after adding new classes

Magento generates proxy classes, factory classes, and interceptors automatically. When you add a new class that uses dependency injection, you may need to regenerate this code:

# Generate interceptors and factories
php bin/magento setup:di:compile

# Clear generated code if something seems wrong
rm -rf generated/code/*
php bin/magento setup:di:compile

If you are getting "Class does not exist" errors for factory or proxy classes, this is almost always the fix. In developer mode Magento generates these on the fly, but in production mode they must be compiled ahead of time.

22. Check your module's sequence in module.xml

If your module depends on another module being loaded first, declare that dependency in etc/module.xml. Without it, your di.xml or layout XML might be processed before the module it depends on, causing hard-to-debug errors.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

One last thing worth mentioning

Magento 2 rewards developers who take the time to understand its architecture rather than fighting against it. The dependency injection system, the plugin architecture, the UI component framework, and the layout XML system all have learning curves but they exist for good reasons. Once you work with them properly instead of around them, your code is more maintainable, survives upgrades better, and plays well with other modules.

The most expensive Magento projects I have seen are the ones where developers skipped the architecture and went straight to hacking. The technical debt accumulates fast and the upgrade path becomes a rewrite. The extra time spent doing things the Magento way upfront is always worth it.

If there is a specific Magento 2 topic you want covered in more depth, drop a comment below.

Building an AI-Powered Product Description Generator in Magento 2 Using PHP & OpenAI

I was helping a client clean up their Magento store last month and they had over 400 products with either no description or a copy-pasted manufacturer blurb that was identical across 30 items. Writing them manually was not happening.

So I threw together a quick module that puts a button on the product edit page. You click it, it grabs whatever attributes are already filled in and sends them to OpenAI, and a few seconds later the description fields are populated.

Not perfect every time, but good enough as a starting point that you just edit rather than write from scratch.

This tutorial shows you how I built it. The module itself is pretty lightweight, maybe 6 files total, and it works on Magento 2.4 with PHP 8.1.

What we are going to build

  • A button in Magento 2 for the admin that says "Generate AI Description"
  • An AJAX controller that sends product attributes to OpenAI
  • A description, short description, and meta content made by AI
  • Automatic insertion into Magento product fields
  • Optional: button to regenerate to get better results

Requirements

  • Magento 2.4+
  • PHP 8.1+
  • Composer
  • An OpenAI API key
  • Basic module development skills

Step 1: Create a Magento Module Skeleton

Create your module folders:

    app/code/AlbertAI/ProductDescription/

Inside it, create registration.php

    use Magento\Framework\Component\ComponentRegistrar;

    ComponentRegistrar::register(
        ComponentRegistrar::MODULE,
        'AlbertAI_ProductDescription',
        __DIR__
    );

Then create etc/module.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="AlbertAI_ProductDescription" setup_version="1.0.0"/>
    </config>

Enable the module:

    php bin/magento setup:upgrade

Step 2: On the Product Edit Page, add a button that says "Generate Description."

Create a file: view/adminhtml/layout/catalog_product_edit.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <body>
            <referenceBlock name="product_form">
                <block class="AlbertAI\ProductDescription\Block\Adminhtml\GenerateButton"
                    name="ai_description_button"/>
            </referenceBlock>
        </body>
    </page>

Step 3: Create the Admin Button Block

File: Block/Adminhtml/GenerateButton.php

    namespace AlbertAI\ProductDescription\Block\Adminhtml;

    use Magento\Backend\Block\Template;

    class GenerateButton extends Template
    {
        protected $_template = 'AlbertAI_ProductDescription::button.phtml';
    }

Step 4: The Button Markup

File: view/adminhtml/templates/button.phtml

    <button id="ai-generate-btn" class="action-default scalable primary">
        Generate AI Description
    </button>

    <script>
    require(['jquery'], function ($) {
        $('#ai-generate-btn').click(function () {
            const productId = $('#product_id').val();

            $.ajax({
                url: 'getUrl("ai/generator/description") ?>',
                type: 'POST',
                data: { product_id: productId },
                success: function (res) {
                    if (res.success) {
                        $('#description').val(res.description);
                        $('#short_description').val(res.short_description);
                        $('#meta_description').val(res.meta_description);
                        alert("AI description ready!");
                    } else {
                        alert("Error: " + res.error);
                    }
                }
            });
        });
    });
    </script>

Step 5: Create an Admin Route

File: etc/adminhtml/routes.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

        <router id="admin">
            <route id="ai" frontName="ai">
                <module name="AlbertAI_ProductDescription"/>
            </route>
        </router>
    </config>

Step 6: Build the AI Controller That Calls OpenAI

File: Controller/Adminhtml/Generator/Description.php

    namespace AlbertAI\ProductDescription\Controller\Adminhtml\Generator;

    use Magento\Backend\App\Action;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    use Magento\Framework\Controller\Result\JsonFactory;

    class Description extends Action
    {
        protected $jsonFactory;
        protected $productRepo;
        private $apiKey = "YOUR_OPENAI_API_KEY";

        public function __construct(
            Action\Context $context,
            ProductRepositoryInterface $productRepo,
            JsonFactory $jsonFactory
        ) {
            parent::__construct($context);
            $this->productRepo = $productRepo;
            $this->jsonFactory = $jsonFactory;
        }

        public function execute()
        {
            $result = $this->jsonFactory->create();

            $id = $this->getRequest()->getParam('product_id');
            if (!$id) {
                return $result->setData(['success' => false, 'error' => 'Product not found']);
            }

            $product = $this->productRepo->getById($id);

            $prompt = sprintf(
                "Write an SEO-friendly product description.\nProduct Name: %s\nBrand: %s\nFeatures: %s\nOutput: Long description, short description, and meta description.",
                $product->getName(),
                $product->getAttributeText('manufacturer'),
                implode(', ', $product->getAttributes())
            );

            $generated = $this->generateText($prompt);

            return $result->setData([
                'success' => true,
                'description' => $generated['long'],
                'short_description' => $generated['short'],
                'meta_description' => $generated['meta']
            ]);
        }

        private function generateText($prompt)
        {
            $body = [
                "model" => "gpt-4.1-mini",
                "messages" => [
                    ["role" => "user", "content" => $prompt]
                ]
            ];

            $ch = curl_init("https://api.openai.com/v1/chat/completions");
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json",
                    "Authorization: Bearer " . $this->apiKey
                ],
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($body)
            ]);
            $response = json_decode(curl_exec($ch), true);
            curl_close($ch);

            $text = $response['choices'][0]['message']['content'] ?? "No response";

            // Split via sections
            return [
                'long' => $this->extract($text, 'Long'),
                'short' => $this->extract($text, 'Short'),
                'meta' => $this->extract($text, 'Meta')
            ];
        }

        private function extract($text, $type)
        {
            preg_match("/$type Description:\s*(.+)/i", $text, $m);
            return $m[1] ?? $text;
        }
    }

Step 7: Test It

  • Go to Magento Admin → Catalog → Products
  • Edit any product
  • Click “Generate AI Description”
  • Descriptions fields will auto-fill in seconds

Bonus Tips

You can extend the module to generate:

  • Product titles
  • Bullet points
  • FAQ sections
  • Meta keywords
  • Category descriptions

Create Helloworld module in Magento

In this article, we are going to discuss about How to create a Helloworld custom module in Magento. Magento is an open-source content management system for e-commerce web sites. Magento employs the MySQL relational database management system, the PHP programming language, and elements of the Zend Framework. It applies the conventions of object-oriented programming and model-view-controller architecture. Magento also uses the entity–attribute–value model to store data.

Step 1: Module Declaration

Note : PCF (PHPCmsFramework)

Create app/etc/modules/PCF_HelloWorld.xml and write below code

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

Step 2: Module Configuration

2.1) Create a controller class app/code/local/PCF/HelloWorld/controllers/IndexController.php

class PCF_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
     $this->loadLayout(array('default'));
     $this->renderLayout();
    }
}

2.2) Create a Block class app/code/local/PCF/HelloWorld/Block/HelloWorld.php

class PCF_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
  // necessary methods
}

2.3) create configuration xml in app/code/local/PCF/HelloWorld/etc/config.xml

<?xml version="1.0"?>
<config>
    <global>
        <modules>
                <PCF_helloworld>
                        <version>0.1.0</version>
                </PCF_helloworld>
        </modules>
    <blocks>
            <helloworld>
                <rewrite>
         <helloworld>PCF_HelloWorld_Block_HelloWorld</helloworld>
        </rewrite>
            </helloworld>
     </blocks>

        </global>
       <frontend>
                <routers>
                        <helloworld>
                                <use>standard</use>
                                <args>
                                      <module>PCF_HelloWorld</module>
                                      <frontName>helloworld</frontName>
                                </args>
                        </helloworld>
                </routers>
        <layout>
            <updates>
                <helloworld>
                      <file>helloworld.xml</file>
                </helloworld>
            </updates>
            </layout>
        </frontend>
</config>


Define Frontend Template :

1. Define page layout in app/design/frontend/PCF/default/layout/helloworld.xml

N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>

    <layout version="0.1.0">

        <helloworld_index_index>
            <reference name="root">
                <action method="setTemplate"><template>page/1column.phtml</template></action>
            </reference>
            <reference name="content">
                <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
            </reference>
        </helloworld_index_index>

    </layout>
   
2. Create template file app/design/frontend/PCF/default/template/helloworld/helloworld.phtml and write down

N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/template/helloworld/helloworld.phtml

Hello World ! I am a Magento Guy..

Hey, new module is ready to run and hit browser with url

http://127.0.0.1/projectname/index.php/helloworld/

and see result.

That's it……..

Magento – Ajax Add to Cart from Product Page Using jQuery

In this article, we are going to discuss about How to create an Ajax based Add to Cart from Product Page Using jQuery in Magento. This is just going to be a quick snippet. One thing I get asked a lot is how to add a product to the cart using ajax and its actually quite easy to do. Now I'm not going to go over how to use jQuery with Magento because there are plenty of tutorials on how to do that. I am going to assume you have jQuery setup in Magento.

<script type="text/javascript"> 
  (function($) 
  { 
    $(document).ready(function() 
    { 
      // Setup the click event 
      $('#product_addtocart_form').submit(addToCart); 
       
    }); 
     
    function addToCart(e) 
    { 
      e.preventDefault(); 
       
      // Here You Should Validate Your Information.  
      // For example if you have options that need to be selected like shirt size 
       
      // Now get the forms data 
      var formData = $('#product_addtocart_form').serialize(); 

      // Now because we are adding the cart through ajax you need to add this so the controller knows that it is ajax and can pass back json if there is an error 
      formData += '&isAjax=1'; 
       
      // Send the form data over 
      $.ajax({ 
        url:$('#product_addtocart_form').attr('action'), 
        type:'POST', 
        data:formData, 
        dataType:'json', 
        success:function(data) 
        { 
          // Do what you want. You have added a product to your cart 
          // I Like to show my persistant cart popup here 
        } 
      }); 
    } 
       
  })(jQuery); 

</script>

Create an Ajax Coupon / Discount Code Box in Magento

In this article, we are going to discuss about How to create an Ajax Coupon / Discount code box in Magento. Basically this will set you up with the new extension you are going to create. The only thing in the tutorial that you do not need to do is putting any information in the controller file. I am going to assume you have followed the tutorial and you are ready to edit your CartController.php. To start off your file is going to look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController 


}

This is our basic controller file. With this any functions we write that have the same name as the Mage Cart Controller will now be overwritten. this is great if you ever need to make changes like adding ajax functionality to any other parts of magento. Next we add the following code and our file should look like this.

<?php 
require_once 'Mage/Checkout/controllers/CartController.php'; 

class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController 

function couponPostAction() 

 // if not ajax have parent deal with result 
  
 if(!isset($_POST['ajax'])) 
 { 
parent::couponPostAction(); 
return; 
 } 
  
 $msg = ''; 
  
 $couponCode = (string) $this->getRequest()->getParam('coupon_code'); 
 if ($this->getRequest()->getParam('remove') == 1) { 
 $couponCode = ''; 
 } 
 $oldCouponCode = $this->_getQuote()->getCouponCode(); 

 if (!strlen($couponCode) && !strlen($oldCouponCode)) { 
 $this->_goBack(); 
 return; 
 } 

 try { 
 $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true); 
 $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '') 
 ->collectTotals() 
 ->save(); 

 if ($couponCode) { 
 if ($couponCode == $this->_getQuote()->getCouponCode()) { 
 $this->_getSession()->addSuccess( 
 $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode)) 
 ); 
 } 
 else { 
$msg = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode)); 
 } 
 } else { 
 $this->_getSession()->addSuccess($this->__('Coupon code was canceled.')); 
 } 

 } catch (Mage_Core_Exception $e) { 
 $msg = $e->getMessage(); 
 } catch (Exception $e) { 
  $msg = $this->__('Cannot apply the coupon code.'); 
 Mage::logException($e); 
 } 
  
 echo $msg; 

}

So basically what we do is check for a POST variable called ajax. If this does not exist then we know not to use our ajax code so let the regular code run or the parents code if you will. If it is available then we continue. The code is essentially the same as it's parent except instead of putting any errors into a session variable and send the browser back a page, we are echoing out any error messages. If the $msg variable is empty then we know there were no errors.

Now we can move on to our form and javascript. Our form should look something like the following

<div class="box"> 
  <strong class="ttl">DISCOUNT CODE</strong> 
  <p>Enter your coupon code if you  have one</p> 
  <form id="discountcode-form" action="<?= $this->getUrl('checkout/cart/couponPost') ?>" name="discountcode-form" method="post"> 
    <div class="text discount-code"><input type="text" name="coupon_code" value="SUBMIT YOUR CODE" /></div> 
    <input type="submit" class="btn-apply" value="APPLY"/> 
  </form> 
</div>

This is just your basic discount code form. You can make any design modifications as you want the only things that are important are the form tags and the input box. Once you have your form you will want to create the following javascript

$('#discountcode-form').submit(function(e) 

  e.preventDefault(); 
   
  $.ajax({ 
    url:$('#discountcode-form').attr('action'), 
    type:'POST', 
    data:'ajax=true&'+$('#discountcode-form').serialize(), 
    success:function(data) 
    { 
      if(data != '') 
      { 
        // Display error message however you would like 
      } 
    } 
  }); 
});

What this script does is takes the action url from the form and passes all of the forms data to our php script using the jQuery ajax function. It then listens for a response. If it getts something other then null you can take that message and display it however you like.

If you have any questions please let me know and as always leave your feedback...

Magento Functional and Factory class groups

In this article, we are going to discuss about the Functional and Factory class groups in Magento. As you know Magento is built based on module architecture, which leads to the requirement that there must be an interaction between modules. Hence, in this part we will learn about the way these modules used.

Definition and Examples of Functional and Factory class groups

Functional Class
  •     Class: only contains functions and static attributes? (not sure)
  •     For example: Mage

Factory Class

  •     Class: consists of functions to create the instance (object) of different Classes. Class depends on input parameters
  •     For example: class Mage

Create an instance of class Mage_Catalog_Model_Product

Mage::getModel('catalog/product')

Generate an instance of class Mage_Catalog_Block_Product_View

Mage::getBlockSingleton('catalog/product_view')

Definition of Instance, the ways to create the instance object in Magento

  • Definition : In OOP, Instance is an Object
  • Create an instance object in Magento

Mage::getModel('catalog/product');
Mage::getBlockSingleton('catalog/product_view');
Mage::app()->getLayout()-createBlock('catalog/product_view')

The process to generate an instance through the function Mage::getModel() is as below:

1) Call function getModel() trong class Mage

2) Call function getModelInstance() in class Mage_Core_Model_Config

3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.

4) Add a new object by the New command:

$obj = new $className($constructArguments);

In this example, $className = 'Mage_Catalog_Model_Product'

Get different instances from different places:

– With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).

– Function Mage::getSingleton() always gives only one object (instance) back.

Steps to setup Authorize.net Direct Post Method in Magento

In this article, we are going to discuss about How to integrate and setup the Authorize.net Direct post method in Magento. Authorize.net's Direct Post Method of payment gateway integration is a great option for Magento sites because it allows for a seamless customer experience while simplifying PCI compliance by keeping all sensitive credit card information off of the Magento server. Configuring Magento for use with Direct Post Method (DPM) is supposed to be quick and easy and it can be as long as you aware of a few less than obvious steps.

Step 1 :

Make sure that your Authorize.net account is a "Card Not Present" (CNP) account. You can confirm whether or not your Authorize.net account is setup for CNP transactions by logging in to the Merchant Account Admin and verifying that you have CNP features like Recurring Billing and Fraud Detection Suite listed in the Tools section.

If you do not see these options or you get errors like "Transactions of this market type cannot be processed on this system" when attempting to authorize payments, the issue is most likely that the account is setup for card present transactions only. If you are using a test account the easiest solution is to just create a new account and make sure to select Card Not Present.

Step 2 :

Make sure to set an MD5-Hash. DPM uses an MD5-Hash as a sort of secret key that is set in in the auth.net merchant admin and the Magento admin to help secure comminication between your magento store and auth.net. If during checkout, after entering credit card information and clicking "Place Order", you get a pop-up alert saying "Response hash validation failed. Transaction declined." the problem is most likely that this is not set.

Step 3 :

Set an MD5-Hash in the Authorize.net merchant admin under Settings > Security Settings > General Security Settings > MD5-Hash. Then enter that same value in the Magento Admin under System > Configuration > Payment Methods > Authorize.net Direct Post > Merchant MD5.

Step 4 :

Make sure that your server's time is set correctly. DPM makes use of a timestamp as a security measure and to help synchronize requests. If the server's time is incorrect you may receive a pop up stating "Gateway error: This transaction cannot be accepted." This is a generic error message. To get more specific error information you can go into app/code/core/Mage/Authorizenet/Model/Directpost.php and either log or dump $response in function process() by doing something like var_dump($reponse); die(); to output the response from auth.net.

If you get a response code 3 with a response reason code of 97 the timestamp value submitted in x_fp_timestamp is either 15 minutes ahead, or 15 minutes behind in Greenwich Mean Time (GMT) (this is the equivalent of 900 seconds ahead or 900 seconds behind in Coordinated Universal Time, or UTC).  You can test your timestamps accuracy using this tool http://developer.authorize.net/tools/responsecode97/ .

On linux you can get the server time using the date command. If it is incorrect consider setting up Network Protocol Time by doing soething like this: http://alienlayer.com/install-and-configure-ntp-to-synchronize-the-system-clock-on-centos/

Step 5 :

Make sure to set the Gateway URL correctly. For test accounts Test Mode should be set to NO and the Gateway URL should be set to https://test.authorize.net/gateway/transact.dll. For Live accounts this should be chagned to https://secure.authorize.net/gateway/transact.dll

Other than that the configuration is pretty straightforward. In the Magento Admin the Authoize.net Direct Post configuration should look something like this:



I hope this helps get you up and running with this very simple and secure payment method. Please feel free to drop any questions in the comments.

Add category name to body class in Magento

In this article, we are going to discuss about How to add the category name to the body class in Magento. The Magento eCommerce platform serves more than 110,000 merchants worldwide and is supported by a global ecosystem of solution partners and third-party developers. Magento is a feature-rich, open-source, enterprise-class platform that offers merchants a high degree of flexibility and control over the user experience, catalog, content and functionality of their online store.

Sometimes you would like to modify the page according to the category. For example, you want to change the banner, background or other things.

Step 1

you can add the next code snippet to the /template/page/1column.phtml or /template/page/2columns-left.phtml or anywhere else you want:

<?php
$class = '';
$currentCategory = Mage::registry('current_category');

if ($currentCategory) {
    $parentCategories = $currentCategory->getParentCategories();
    $topCategory = reset($parentCategories);
    $class .= $topCategory->getUrlKey();
}
?>

Step 2

Next, append the $addClass variable to the body class like this:

<body <?php echo $this->getBodyClass()?' class="'.$this->getBodyClass() . " " . $class . '"':'' ?> >

Steps to Install a premium Magento extension

In this article, we are going to discuss about how to install a premium extension in Magento. There are two ways you can install premium Magento extensions and each different method has it's own merits. Before installing any Magento extension, you should disable your Magento Cache and the Magento Compiler. After installing the extension, you should always recompile the Compiler instead of simply enabling it again.

Magento Connect - Downloader

It is possible to install the .tgz extension file automatically through Magento Connect (Downloader). To access your Magento Downloader, add /downloader/index.php to the end of your Magento URL. You can login to the Downloader using your Magento Admin login details.

Once you have logged in, upload the .tgz file using the 'Direct package file upload' form. This will automatically install the extension for you.

Upgrading using the Downloader

If you want to upgrade a premium Magento extension using the Downloader, you must first uninstall the extension. You can do this automatically via the Downloader and then install the new updated version using the steps outlined above.

Installing Manually

Installing Magento extensions automatically via the Downloader is the best option. It is much easier and makes it easy to remove an installed extension. That being said, there are many problems with the Downloader that may stop it working for your site (permissions being the main problem). If you are unable to use the Downloader, you can install the extension manually. You can also add the extension to the Downloader so that if in future you fix your Downloader, the extension will be registered there and can be upgraded or uninstalled automatically.

To install the extension manually, extract the files from the .tgz file. Next, ignore the package.xml (this is used by the Downloader to automatically install the extension) and merge the rest of the files with your Magento site using either FTP or SFTP. Refresh the Magento Admin and the extension will be installed.

To register the extension with your Magento Downloader, copy the name of the .tgz file (not including the .tgz part) and rename package.xml as the file you just copied followed by '.xml'. Upload this file to var/package/ and the extension will be registered in your Downloader.

Installing Magento WordPress Integration Add-On Extensions

Add-on extensions for Magento WordPress Integration are just like regular Magento extensions and can be installed using either of the methods outlined above. Before installing though, always ensure that Magento WordPress Integration is upgraded to the latest version. This will reduce the chances of encountering any problems with your new add-on extension.

Steps to add/configure Specials block carousel in Magento

In this article, we are going to discuss about How to add/configure specials block carousel in magento. The Magento eCommerce platform serves more than 110,000 merchants worldwide and is supported by a global ecosystem of solution partners and third-party developers. Magento is a feature-rich, open-source, enterprise-class platform that offers merchants a high degree of flexibility and control over the user experience, catalog, content and functionality of their online store.

Step 1 :

To add/configure specials block carousel, we need to observe that this block/ might not be available on your specific template. Open admin part and go to CMS -> Widgets.

Step 2:

You should see Catalog Sale Product Carousel or Catalog Sale Product record widget when you've got installed the template with pattern information. just open widget so as to configure it. because widget is just not installed we wish to add and configure it. click on on Add New Widget occasion.

Step 3:

Select type of block. You must choose Catalog Sale Product Carousel or Catalog Sale Product checklist. select the template.

Step 4:

Now we need to specify widget occasion title, make a choice retailer views and specify order during which block will appear.

Step 5:

Click on on Add structure replace. In structure update you must choose web page and area by which you wish to set the block.

Step 6:

Open Widget choices and specify choice of products in order to seem in block.

Step 7:

Retailer adjustments and clear Magento cache. on this tutorial you will see clear Magento cache.

Step 8:

Refresh the house web page. Specials block seems on our web page.

Steps to Add Icon for New Products in Magento

In this article, we are going to discuss about How to add Icon for new products in Magento. As your inventory rises it's always very necessary to make your products stand out using an unique icon. Visitors to your website will be able to notice which products are newly arrived as the icon will show up in wherever you set it to in your theme.

Step 1: Manage attributes

Go to Catalogue -> Attributes -> Manage Attributes. Set up a new attribute at this page and call it 'Boolean'. Set its ID as new_product. Under your advanced options, you will have the option to select it as a front end product. Do this. Now you simply have to add the new attribute to your custom attribute if you are using one. If not, set it to default. Save the new product.

You will now have a new product in your catalogue which has a Boolean flag set to yes. The next stage involves taking this new product icon and putting it in your front end.

Step 2: Make it show

Now that you have a product icon with a Boolean flag, it's time to make this show on your front end. This is achieved by accessing template files: templates/catalog/product/list.phtml and templates/catalog/product/view/media.phtml.

<div class="product-image">
<?php if($_product->getNewProduct()) { ?>
<div class="new-product"></div>
<?php } ?>
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')
->init($_product, 'image').'" 
alt="'.$this->htmlEscape($this->getImageLabel()).'" 
title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
</div>

As you can see, above, your new product is shows in '$_product->getNewProduct'. The next step is to ensure that your CSS is set up to show your product with Boolean flag. You need to make the product_class relative to the position of the icon. So:

.products-grid .product-image { position: relative; display:block; width:244px; height:156px; margin:0 0 10px; }
.new-product {position: absolute;right: 0;top: 0;width: 65px;height: 66px;display: block;z-index: 2;background: url(../images/new-product.png) no-repeat;}

Step 3: Save

Save your changes and ensure that your code is correct before doing so. Now, every time you add a new product and it goes on sale through your front end, it'll have an icon and Boolean flag.

Steps to Install Magento On Ubuntu

In this article, we are going to discuss about How to install Magento on Ubuntu. Magento is a feature-rich, open-source, enterprise-class platform that offers merchants a high degree of flexibility and control over the user experience, catalog, content and functionality of their online store.

Here are the steps to install Magento on ubuntu with sample data.

Create a database :

Use the below command to create a database for magento on ubundu.

mysql -u root -p

mysqladmin -u root -p create magento_test;

mysqladmin -u root -p reload;

GRANT ALL ON magento_test.* TO magento_test@localhost IDENTIFIED BY 'magento_test_password'

Install Magento :

This is almost the same as above, except you don't need to know the directory name. You will only have to replace DBHOST, DBNAME, DBUSER, and DBPASS.

wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz

tar -zxvf magento-1.7.0.2.tar.gz

wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz

tar -zxvf magento-sample-data-1.6.1.0.tar.gz

mv magento-sample-data-1.6.1.0/media/* magento/media/

mv magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql magento/data.sql

cd magento

chmod -R o+w media var

mysql -h DBHOST -u DBUSER -pDBPASS DBNAME < data.sql

chmod o+w var var/.htaccess app/etc

cd ..

rm -rf magento-sample-data-1.6.1.0/ magento-1.7.0.2.tar.gz magento-sample-data-1.6.1.0.tar.gz magento/data.sql

Go to www.DOMAIN.NAME/magento/ and follow the online installation guide.

Errors may occur during fresh installation :

WARNING: your Magento folder does not have sufficient write information

following is 100% safe to run from the directory where Magento is installed:

find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod o+w var var/.htaccess app/etc
chmod 550 mage
chmod -R o+w media

If that is not working, try setting all directories to 777 by doing this:

find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 777 {} \;
chmod o+w var/.htaccess
chmod 550 mage

http://www.magentocommerce.com/wiki/groups/227/resetting_file_permissions

Steps to add WYSIWYG editor to Magento backend

In thia article, we are going to discuss about steps to add WYSIWYG editor in Magento admin backend. WYSIWYG editor is a tool that helps easily format or edit text or html code as you want. By adding WYSIWYG editor to your backend, you will have a visual editor rather than dealing with all code.

However, this task seems not as simple as adding other fields. It requires inserting some javascript and css files to make the editor work. Thus this post may be a good resource for you. Just keep on reading and follow the steps below to learn how to add WYSIWYG editor to Magento backend.

Step 1 : Enable WYSIWYG editor in your field

Open the file "app/code/local/[your_name_space]/[your_module]/Block/Adminhtml/[your_block]/Edit/Tabs/Form.php" and add the below codes.

$fieldset->addField('description', 'editor', array(
'label' => Mage::helper('customerreward')->__('Description'),
'title' => Mage::helper('customerreward')->__('Description'),
'class' => 'required-entry',
'required' => true,
'name' => 'description',
'wysiwyg' => true,// enable WYSIWYG editor
));

Step 2: Add js and css files to controller action

You can follow either of these ways:

Step 2.1 : Use PHP code in your controller action:

Open the file "app/code/local/[your_name_space]/[your_module]/controllers/Adminhtml/[controller_name]Controller.php" add the below codes.

$this->getLayout()->getBlock('head')
->setCanLoadExtJs(true)
->setCanLoadTinyMce(true)
->addItem('js','tiny_mce/tiny_mce.js')
->addItem('js','mage/adminhtml/wysiwyg/tiny_mce/setup.js')
->addJs('mage/adminhtml/browser.js')
->addJs('prototype/window.js')
->addJs('lib/flex.js')
->addJs('mage/adminhtml/flexuploader.js')
->addItem('js_css','prototype/windows/themes/default.css')
->addItem('js_css','prototype/windows/themes/magento.css');

Step 2.2 : Use layout file:

Open the file "app/design/adminhtml/default/default/layout.xml" and add the below codes

<referencename="head">
<actionmethod="setCanLoadExtJs"><flag>1</flag></action>
<actionmethod="setCanLoadTinyMce"><flag>1</flag></action>
<actionmethod="addJs"><script>lib/flex.js</script></action> 
<actionmethod="addJs"><script>mage/adminhtml/flexuploader.js</script></action>
<actionmethod="addJs"><script>mage/adminhtml/browser.js</script></action>
<actionmethod="addJs"><script>prototype/window.js</script></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/magento.css</name></action>
<actionmethod="addItem"><type>js</type><name>mage/adminhtml/wysiwyg/tiny_mce/setup.js</name><params/></action>
<actionmethod="addItem"><type>js</type><name>tiny_mce/tiny_mce.js</name><params/></action>
</reference>

Now, you can view this form shown in your Magento admin backend.

Steps to add Icon to New Products in Magento

In this article, we are going to discuss about steps to add Icon to new products in Magento. As your inventory rises it's always very necessary to make your products stand out using an unique icon. Visitors to your website will be able to notice which products are newly arrived as the icon will show up in wherever you set it to in your theme.

Step 1 : Manage attributes

Go to Catalogue -> Attributes -> Manage Attributes. Set up a new attribute at this page and call it 'Boolean'. Set its ID as new_product. Under your advanced options, you will have the option to select it as a front end product. Do this. Now you simply have to add the new attribute to your custom attribute if you are using one. If not, set it to default. Save the new product.

You will now have a new product in your catalogue which has a Boolean flag set to yes. The next stage involves taking this new product icon and putting it in your front end.

Step 2 : Make it show

Now that you have a product icon with a Boolean flag, it's time to make this show on your front end. This is achieved by accessing template files: templates/catalog/product/list.phtml andtemplates/catalog/product/view/media.phtml.

<div class="product-image">
<?php if($_product->getNewProduct()) { ?>
<div class="new-product"></div>
<?php } 
$_img = '<img id="image" src="'.$this->helper('catalog/image')
->init($_product, 'image').'" 
alt="'.$this->htmlEscape($this->getImageLabel()).'" 
title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
</div>

As you can see, above, your new product is shows in '$_product->getNewProduct'. The next step is to ensure that your CSS is set up to show your product with Boolean flag. You need to make the product_class relative to the position of the icon. So:

.products-grid .product-image { position: relative; display:block; width:244px; height:156px; margin:0 0 10px; }
.new-product { 
position: absolute;
 right: 0;
 top: 0;
 width: 65px;
 height: 66px;
 display: block;
 z-index: 2;
 background: url(../images/new-product.png) no-repeat;
}

Step 3 : Save

Save your changes and ensure that your code is correct before doing so. Now, every time you add a new product and it goes on sale through your front end, it'll have an icon and Boolean flag.

Procedure to run Magento codes externally

In this article, we are going to discuss about how to run the Magento codes externally. If you're working with Magento often you'll find sometimes you need to use Magento functions and classes outside of the Magento platform. This can be easily achieved with the following lines of code.

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

// Now you can run ANY Magento code you want
// Change 12 to the ID of the product you want to load
$_product = Mage::getModel('catalog/product')->load(12);
echo $_product->getName();

This was only a quick post but hopefully it will be useful to someone.

Here's an example how to get the site navigation.

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

$_layout  = Mage::getSingleton('core/layout');
$_block   = $_layout->createBlock('catalog/navigation')->setTemplate('catalog/navigation/left.phtml');
echo $_block->toHtml();

Prototype Javascript validation in Magento forms

In this article, we are going to discuss about How to use the prototype javascript validation in Magento forms. Using Javascript validation in forms will improves the usability and efficiency of the website. It will leads to a better web 2.0 look and feel.

Javascript Validation in Magento

In Magento, they are using the form.js (js/varien/form.js) file to provide the abstract JavaScript functions for forms by default. To achieve this validation, form.js uses the Validation class which is part of the Prototype Javascript library. It works by checking form inputs for certain class names. Each class name tells the validator to perform certain checks on the value inside the input.

Custom Form Validation

Adding Javascript validation to your own forms is extremely simple. First, you need to create a Form (form.js) object to represent your form.

<script type="text/javascript">
//< ![CDATA[
  var myForm= new VarienForm('formId', true);
//]]>
</script>

The first parameter, in this case formId, is the ID of your form.

The second parameter defines whether or not the first input field in the form should steal the cursor focus. If set to true, the cursor will automatically be moved into the first input field and any user input will be entered into this field. You can disable this functionality by setting the second parameter to false.

Now that you have created a Javascript object to represent your form you need to add some validation rules to your form inputs.

<label for="name">Name *</label>
<input type="text" id="name" name="name" value="" class="required-entry"/>
<label for="email">Email Address *</label>
<input type="text" id="email" name="email" value="" class="required-entry validate-email"/>

Notice the classes 'required-entry' and 'validate-email'? These both tell the classes to apply certain validation rules on the input fields. If any of the validation checks fail, the form will not be submitted and the user will be alerted to the errors.

Magento Javascript Validation Classes

There are many more validation classes you can assign and I list them here as a reference. For more information on this please use Google, experiment with the code or contact me via my email or the contact form.

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

Create category navigation listings in Magento

In this article, we are going to discuss about How to create the Category navigation listings in Magento. This below code will display the categories and the current category's subcategory or categories and all sub-categories. The below code is working fine. I have recently stumbled on a much better, neater way to accomplish this. This method requires less database interaction and therefore should render faster on the front end.

Listing Categories in Magento 1.4.1.1 and Above

Before start, you need to make sure the block that you're working is of the type "catalog/navigation". If you're editing "catalog/navigation/left.phtml" then you should be okay.

This can be slow and often loads in more information than we need for a simple navigation menu. This version uses the Varien_Data_Tree class.

<div id="leftnav">
    <?php $helper = $this->helper('catalog/category') ?>
    <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>
        <ul id="leftnav-tree" class="level0">
            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                    <a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
                    <?php if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                            <script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
                        <?php endif; ?>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
        <script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
    <?php endif; ?>
</div>

If you copy and paste the above code into "catalog/navigation/left.phtml", it should work straight away. It should list all categories and any first level subcategories of the current category. You can modify this code to display all sub-categories by removing the IF statement at line 9.