Make a clean sweep of commons Magento cache_lifetime workarounds usage

As I mentioned before, Magento cache policy API is based upon the Zend Framework Zend_Cache component. In this cache policy, there are three elements :

  • Cache key that defines the unity of the data we want to cache
  • Cache tags that allow to cluster our cache data
  • Cache lifetime that defines the duration within we consider that our stored data are valid and do not need to be rebuilt

My current topic will be about this latest point: cache lifetime. Its usage is quite simple: we define a duration while data will be stored in cache; during this period, data is always considered as valid, and so, not rebuilt. After that, even if data exists in cache, it will be rebuilt because considered as expired. Simple, no?

But we can hear so many things about cache lifetime usage that it seems interesting to evoke some specific points about its usage in Magento

What happens when Magento cache lifetime is specified as null?

When Magento cache lifetime is considered as null?

Excluding case you have defined a getCacheLifetime method which returns null value, this case occurs when you do not define the cache lifetime on one object which extends Varien_Object:

  • When rendering block content, Magento will call the getCachelifetime block method
  • If you have not defined a getCacheLifetime method, Magento will use Varien_Object __call method to retrieve cache_lifetime from attribute _data
  • If this index does not exists in _data, __call will return null

How is managed cache lifetime null value by Magento for block data?

All blocks extends Mage_Core_Block_Abstract. This class provides the following cache management:

As you can see, if lifetime is null the Magento Cache API will never fetch something from cache, so rebuild each time the block content. But also nothing will be stored in the cache(_saveCache method check if also there is a non null lifetime before save)

If you do not set up a cache lifetime for a block content, it will never be cached

How is managed cache lifetime null value by Magento blocks for non block data?

The cache API can also be used for other things than block output. This is the case for configuration cache. In this case, the control made by Mage_Core_Block_Abstract does not exist, and data will be cached: we’ll see that if cachelifetime duration is null for something else than block, it will use the default lifetime value like id you set up false as a cache lifetime value: 7200sec (2 hours)

What happens when cache lifetime is set up to 0 ?

Sometimes, we can hear that setting 0 as cache_lifetime duration disable cache. No, and this is for the following reason: 0 is a valid cache_lifetime duration.

Magento will define the timestamp until you consider your block content as valid with the following rule: current timestamp of data generation + cache_lifetime; so calculated expiration time will be the generation time. For sure, next time you’ll check if data is in cache and valid, you’ll compare new timestamp with expired timestamp, and there is a great probability that your current timestamp will be later.

Setting 0 as cache lifetime duration render your cached block content always expired

This is one of the worst case, because, each time you build content, you save it in cache, and invalidate it next time you’ll check it

What happens when cache lifetime is set up to false ?

The Zend Framework lifetime management for false values

Every cached backend used in Magento inherits from the Zend_Cache_Backend class

When saving content, Zend_Cache_Backend class will calculate the expiration timestamp trough the Zend_Cache_Backend::getLifetime method. If specified lifetime === false, backend use a default duration stored in its attributes

If you check Zend_Cache_Backend class, you’ll check that this value is hard_coded as 3600 sec (one hour)

But our content is stored longer, why?

Magento forces a default lifetime in its frontend

When the Magento cache API initializes the cache frontend object in the Varien_Cache_Core model, it merges cache options with directives options

This is the case for the cache_lifetime duration: default cache lifetime duration specified on Varien_Cache_Core is merged with directive options

But Varien_Cache_Core class extends Zend_Cache_Core. So when backend will be set up to frontend, we’ll use the native Zend Framework behaviour and so, merge frontend options as a backend directives.

So for all of our backend usage, because Magento forces usage of a Varien_Cache_Core frontend, default lifetime will be set up as 7200s

If your lifetime is set up to false, by default your block will be considered as valid during 7200s

Using Setups to deliver application software with Magento

A long time ago,

in a (not) so far away office,

a Magento project is coming

we could hear something like this

Guys, I have an error when I display product sheet: “table does not exist”, what’s wrong?

The little guy on the openspace corner who talks like a robot answered him: It’s normal, you must execute the SQL script create_table.sql located in var/temp

This is not about the force I’ll talk about, but the power of the dark side, the lazyness: How Magento can help us to solve deployment problems? With the magento setup scripts

Introduction to Magento setup

Main interest of the Magento setup

Have you ever asked how Magento install its own database? This setup process is run against the Magento setup scripts: all database tables, initials configuration values or required records are inserted with these scripts: no need to play any SQL, all is managed with the native setup Magento API

Files involved in Magento setup

This mechanism is strongly linked with Magento modules architecture: if your module requires a dedicated table, it must be able to create the prerequisite to work properly. Another case study is when project is started: you made some modeling choices, and those ones require perhaps a specific configuration. it’ll very interesting that this configuration will be set up automaticly on each location (developpement, testing, prod, …), without any human action.

After reading this post, if you check what is executed by Magento during database setup, you’ll see that each module is responsible for its own setup:

  • Mage_Catalog create the catalog attributes
  • Mage_Checkout create the tables of agreements
  • etc

All modules files involved in setup are located in the module sql subfolder

Let’s see how it works

Main working

How does Magento find the module list that have some setups to run?

As I mentionned before, all is based upon the configuration files located in the app/etc/modules folder. When configuration is merged, Magento knows which are active modules.

From this merged configuration, Magento will find the setup list to run.

But not every module will have some setup. To know which modules have installers, it does not browse the sql folder for each module but looks for some dedicated XML nodes in configuration. These nodes depend on resources and are defined like this:

Without this node, and even if you have defined some sql scripts in your sql subfolder, nothing will happen

Now Magento can iterate through the configuration saved in cache, look for the <config><global><resources> to find the availables resources defined. if this resource has a setup subnode defined, it will be known as “with setup”

In which state are your Magento module sources? the version notion

Your module sources can be in 3 differents states with your Magento:

  • Install mode: you have just installed the module source on your Magento, but for now nothing has already been set up
  • Update mode: you have just made an update of your module sources, and the new setup has not already been played.
  • Downgrade mode: you’ve made a downgrade of your module sources. And now, the state of your database is too far from your module sources

All these states are managed with two version numbers: the current version number of your sources and the latest installed version number of your module in database

Magento current installed module version number

This number is defined in the core_resource table. This table contains for each resource the latest version number installed

Magento current module version number

This number should be defined in the config.xml file located in module etc subfolder with the following node:


Is there a specific format for version number?

No, Magento does not expect a specific format. It’s a versionning problem and often we define the version number with a format like X.Y.Z, where:

  • X: the major version number, and increases when you review the software architecture
  • Y: the minor version number, and increases when you add a new functionnality in module
  • Z: the bug fix version number, and increases when you fix a defect

What’s important is that your version number means something and changes according to your source code update

How does Magento find the list of setup to run?

The Magento resource defines where are located files and if there is some setup defined for your module

How does Magento link resource name with file path to find script list involved in setup?

The resource name is used to find where are located setup scripts:


This is in this folder that Magento will find the script used in setup

Setup state will help Magento to find possible file list to run

Then Magento will check in which state are your modules sources:

  • install: there is no db record for your %resource_name% in core_resource table
  • upgrade mode: core_resource database record is lower than the version defined in the module source
  • downgrade mode: core_resource database record is higher than the version defined in the module source

According to this state, Magento defines in which case you are:

  • install (Mage_Core_Model_Resource_Setup::TYPE_DB_INSTALL)
  • upgrade (Mage_Core_Model_Resource_Setup::TYPE_DB_UPGRADE)
  • rollback (Mage_Core_Model_Resource_Setup::TYPE_DB_ROLLBACK)

Version comparison between already installed version and source version is based upon the version_compare PHP method

Possibles file list to run

Here’s how Magento knows if there are some scripts to run. Let’s see how this file list is built

Can we use subfolders to organise our setups scripts in app/code/%Your_Module_CodePool%/%Your_Module_Namespace%/%Your_Module_Name%/sql/%resource_name%/ folder?

First, Magento iterates on these folders with dir class and so, will iterate only in this subfolder; so you cannot put your scripts in a subfolder, they won’t be played

Which extensions can be used to run setup scripts?

Magento iterates on all files and expects to find .SQL or .PHP files to run.

As a best practice, you must use PHP file to avoid using hard coded table names and field names: For example Magento allows you during install to provide a table name prefix. The easyest way to find this prefix without using PHP setup scripts.

How can Magento take care of the database server type used with your Magento? the database connexion connector type

On paper, Magento can use multiple databases server types. Default one is MySQL.

By default, Magento setups scripts can take care of the setups differences between each database servers with the connector type: Connector type is defined by the configuration node model used by the connection defined to run your module. By default, all connections of your Magento will inherit the connection default_setup, defined in the app/etc/config.xml. As you can see in the following screenshot, this node is by default defined as mysql4

When determining which scripts can be involved in the setup subfolder, Magento will look for the files matching the pattern %connector_type%-%source_state%-.+

How does Magento avoid playing two times the same setup script? the role of version

After finding all files matching the previous pattern, Magento reduces the list according to the current database state to only required versions with the version compare usage

At the end of this step, every script in the available list must be run

Running the scripts: how does Magento increase resource version number in core_resource table?

Plus the setup list to run, Magento will include one other that follows. Version number in core_resource table is not updated at the end of all the scripts, but after a script has completed normally. So if you need to restart the setup process, you’ll restart at the last error setup script

Conclusion about this Magento installer mechanism

This mechanism is really helpfull to deploy and normalize your different projects locations: by setting these scripts, you are sure that every location has the same required configuration values, concepts specified. Deploying a new location for a new developper or for the production server will be more easily because all required configuration values, tables, etc will be already set up.

One other great advantage of these scripts is to allow you to versionate only the scources code: no SQL state versionning requirement, all is managed through sources modules files

Develop and test setups scripts may have a cost to take care, but reduce risks based on misconfiguration or a forgotten SQL script

Magento guide: the three concepts of a Magento website context

Magento embeds a native multistore model that allows to configure multiple e-commerce models on the same magento source. If you are a Magento beginner, perhaps you are quite a bit lost with these stores, websites and views context. Each one has a dedicated role, and you should respect them, otherwise you would have to modify deep Magento’s working layer which would be quite difficult.

Screenshot of the stores management administrative panel available through the Magento administrative panel System > Stores Management

The magento websites are used to define your way of working :

  • Define a sales catalog
  • Configure the price rules management
  • Configure how customer accounts are shared between all yours stores

Define a sales catalog in a Magento website

Your catalog is manageable through the administrative panel catalog > Manage products. You can define there all your products data: name, description, price, etc

But this is not because you have enabled a product in this administrative panel that it will be salable: it needs to be part of a sales catalog: what do you want to sell on your store? All your products? Only some elements of your work?

For example, take a look at the LVMH group. This group owns Dior fragrance, Louis Vuitton bags, etc… Imagine they want to build a Magento to sell all their catalog (and if you want, you can contact me :)), they would want to sell each dedicated brand products in a dedicated store. To do that, they need two things:

  • They will first describe all their products in Magento back-office: product’s names, reference in their informatic system, etc. Afterthat products are editable, but not salable

  • Secondly, they’ll have to publish them in their sales catalog to ensure that only fragrance will be published in the Dior dedicated store, and only bags will be sold through the Louis Vuitton online store

To do that, products need to be linked to a website. This is available through the product sheet website tab

Checking the website checkbox will publish your product in the related sales catalog

So you should have at least one website per sales catalog

Are your sure? I’m not LVMH group, have only one online store, and I never do that, and I’ve not the website tab …

When you are in a single website context, all is done in background without any action

Define the scope of your prices in Magento through website

At this point you should know how to define your sales catalog

Now imagine that your business model will propose two different prices for the same product: a discount store and a normal one for example. If your prices rules are not managed with conversion rates, you should configure the price rule scope as website instead of global

This configuration value is available though the administrative panel system > configuration > catalog > prices > Catalog price scope

Magento adminstrative panel which allow to configure the price scope in a multistore context

You can with this rule apply a specific price for an article in a dedicated sales catalog

Configure how customer accounts are shared between websites

Websites allow also to configure the visibility scope of your customers account.

Suppose now that Amazon would migrate to Magento. (Yes perhaps you need to do a benchmark for other solutions, but it’s another problem 🙂 ). Do they want the customer accounts to be shared between,, and Sharing same shipping address, same customer email account, etc? If so if you update your customer account on, data will be also updated on

Customer accounts scope is a configuration value available through the system > configuration > Customers > Account sharing scope.

Screenshot of the account sharing option available through the administrative panel System > Configuration > Customer configuration

This option value will define how your customer accounts will be shared between each website

Why is it so important to well define the store model on your Magento?

As you can see, website define deep main work of your client and for this reason website are probably the most important degree of organization in the Magento multistore model. Updating a store model during a Magento project life is not an easy task, and for this reason, you should well define it at the beginning of your project. So be sure to ask yourself the revelant questions

How Magento load your modules configuration? the activation files located in app/etc/module folder

This post will be the first part of two topics based on the Magento configuration and on how this configuration is cached. If you are already experimented in Magento, this topic is probably something you already know, but I hope it would be helpfull for those who start with Magento

Magento is based on a module architecture. Each module can define its own components, blocks, scripts, models, databases connections, etc. Each module can embed multiples configurations files, but the main one is the config.xml file located in the module etc subfolder. To avoid reading each configuration file each time, every module configuration is saved in cache. Here’s how it works

First, Magento requires to know which scripts must be played: Magento load each XML files in app/etc/modules folder to find which are the modules we want to declare

Module activation file: the files list in app/etc/modules

For a quick reminder, files located in app/etc/modules folder should have the following structure:

<?xml version="1.0" encoding="UTF-8"?>
                   <active>true</active><!--true or false -->
                   <codePool>local</codePool><!-- local / core or community -->
                      <!-- list of %Module_Identifier% prerequise to make our module works fine -->

active node in Magento XML activation file

This node informs Magento that we want to use this module. Expected values are case sensitives and should be true or false. If you set false, there will be no output, no override, no functionnalities, no layout updates

Magento bootstrap will only take care of the modules which are active true. Yhe Other ones are ignored.

codePool node in XML activation file

Codepool values are the subfolders located in app/code folder. As I mentionned before in my post on the loading APIs, changing codePool can modify how your classes are loaded, and so, if they can be overloaded or not

CodePool value provided in the activation XML file will help Magento to know where to look for our module configuration file

Module identifier

Module identifier allow Magento to link the configuration file with the module folder: The expected value for the Module identifier is based on %Namespace%_%ModulePath%: with this value and the codePool, magento is able to determine where to look for our module etc/config.xml file

XML identifier

I’ve noticed that encoding and version are attributes required for the XML files header. Truly, only version is required. But take the habitude to also note your encoding, and normalize your XML version as UTF-8

After browsing the app/etc/modules and read all XML files in, Magento knows which modules must be activated and loaded in our Magento

Dependancy tree between modules: the depends node in Magento XML module activation file

This node is not also required. But it can modify how setups are played: without dependancies, modules identifiers are sorted in alphabetical order. If your namespace starts with a character before M (for Mage namespace), do not define the dependancies and deploy all your data without an existing magento database, your setup will be runned before the Magento’s one, and so, there is a big risk that it fails if you call some Magento entities. So take also the habitude to define at least Mage_Core in your module dependancies.

Sometimes we can see that dependancies are defined in your module configuration file (config.xml). because dependancy tree is built before config.xml has been read, it has no interest

Merge configurations files

After reading the activations files, Magento knows which modules it must load (he knows namespace_module path, and codePool). So it can now go reading each modules configurations defined in module configuration file, the config.xml file: all config.xml files for active modules will be merged in a single one XML structure which will serve as global configuration

Now magento can save all data in cache

How to organize your modules definition in activation files?

Because it’s a XML structure and they are merged, you have two choices for your modules

  • Define each module location in a dedicated file
  • Define all yours modules locations in an only file

Magento chooses to use only one file to define all its modules: the file app/etc/modules/Mage_All.xml

If you work without versionning system (like git or subversion), there is no risk to work with only one file

But if you are numerous to work on the same project, you should prefer to use one file per module for the following reasons:

  • You can reduce conflicts risks (the less developpers work on the same file, the less risk you have to get conflicts)
  • If you want to publish some modules on Magento connect, you should make reworks in a single file usage


Is there a way to check that my module is well loaded?

The quickest way to check if your activation file is well read by Magento is in the Administrative panel available through System > Configuration > Advanced: If your module identifier is listed there, all is fine. In other cases, be sure to check its syntax

Thank you for this topic. When will be the second part published?

some suggested me to publish more often 🙂 Next part should be post quicker

Server side validation for configuration values in Magento with backend: an how-to

I wrote few times ago a tutorial which explains that we can validate configuration values in Magento from the client side

But as you know, (and it’s not valid only for Magento) even if you validate the format from client side, you must also validate data from server side: this is the only way to be sure that expected data has been provided

The model provided by Magento to validate data is the backend

What is a backend?

Backend introduction

A backend is a model object used to do treatments from server side.

The common usage for these backends is to make post treatments when saving configurations values or attributes

Default structure for Magento backend configuration

In Magento, backends are models and so, are called with getModel instruction. This is done by the following instruction in Mage_Adminhtml_Block_System_Config_Form class:

So as you can see in the source code screenshot, backend models used for configuration values must be instances of Mage_Core_Model_Config_Data

Ok, it’s fine, but what are their roles?

Common Magento backend configuration usage

Magento backend has two majors roles. All is based on the fact that Mage_Core_Model_Config_Data class extends Varien_Object class, and so, can have the common method structures _beforeX and _afterX. Here’s their common usage:

Validate data: the _beforeSave Event

This step is launched on the _beforeSave method: you make your controls on this event, and if the value is not the expected one, you throw an Exception. It will be catched in higher level, and will be displayed in configuration form

Data won’t be saved if there is an error on this event

Prepare data: the _beforeSave Event

The _beforeSave method can also be useful to format data

Data won’t be saved if there is an error on this event

Do post treatment: the afterSave Event

Post treatments will be done after data has been saved. In configuration values, they are realized after configuration is recorded in core_config_data table

If you throw an error in this step, configuration value is already saved

Other possibles Magento backend usage

Mage_Core_Model_Config_Data extends Varien_Object and so, all the events availables on this class can also be used on a defined backend model. But for now, I haven’t seen their usage. Do you?

Ok, nice, backend seems really fine. But how can we define our own backends models?

How to define a backend for a configuration value in Magento?

This is very easy with Magento API for configuration values: we have only to define a node backend_model for our field structure. All is done in your system.xml module file

Here’s an example of backend_model definition:

For this field frequency, we will define our backend model MExplained_Criteo_Model_System_Config_Backend_Criteo_Cron

If backend_model node is not defined in system.xml field, there is no backend defined for our configuration field, and so, no treatment made server-side

Conclusion on Magento backend models

Backend models are classes which allow you to make pre and post treatments from server side. This is the only secure way to ensure that expected data has been provided!

I’ve used the Configuration API as example because I’ve found this API very simple and a good example for backend usage. But all functionnalities provided for backend configuration data is also available for attributes. Take a look at the eav_attribute table and you’ll see that you can also provide your own backend models for your attributes (except that they do not extend the same class)

Backend models are Magento models and so, can also be overwritten like other magento classes

With client-side validation, you’ll have a complete toolkit to validate configuration values. And as you can see, validating these data from server side and client side should not be more than half an hour. So it’s a shame to see that numbers of modules do not use these validations. For example, Owebia_Shipping module, a shipping module requires to set up a json configuration value. If this module had a backend usage to validate that configuration value provided is a valid json string, perhaps many of you would have gained time. That’s what you call  quality of service, no?

Configure how web crawler will index your Magento website

ROBOTS.txt is a standard which provides instructions for web crawlers that index your website. We'll see in this post how Magento allows us to manage robots.txt, and how we can extend its work.

Robots.txt, a quick overview

What is robots.txt ?

W3c explains us that robots.txt is a standard way integrated in HTML to tell search engines bots how you want them to index your website:

  • Do you want to allow them to index the page content?
  • Do you want to allow them to follow internal links to search new pages to index?

All these actions can be controlled by the following instructions:

  • index / noindex: manage your wish to index the current page content
  • follow / nofollow: manage your wish if you want that bots can search for links in current page

Hum, interesting, how we can set up these values?

Where do I set up robots.txt?

There is two ways to set up robots informations:

Robots.txt file

By default, web crawlers will search in your document root directory for a file named robots.txt. In this file, we will define to web crawler our global indexation policy.

If this file does not exist, web crawler will check in the page header

With the ROBOTS meta header

We also have the choice to manage the robots informations directly in page headers

In this case, we send in the page header a meta name "ROBOTS" which provides our indexation preferences. Here's an example of possible header sent

<meta name="ROBOTS" content="NOINDEX,NOFOLLOW" />

What's the interest of setting a good robots.txt policy?

Interest of these method is that you can control how indexers work:

  • I suppose that you wish to index your catalog pages
  • Do you really require that checkout page was indexed?
  • Do the links provided in cart page require an indexation?

Ok, I'm convinced. But Magento does not provides a mechanism to set up robots values?

How Magento manage robots ?

Magento provides a mechanism to configure robots values in header. This administrative panel is available in the System > Configuration > Design > HTML Head. Here's a screenshot:

As you can see, we can define the index / follow property but only in a global context: all pages will have the same meta ROBOTS values: so for now we are unable to provide differents robots instructions for our pages. Furthermore, if you do not set up a configuration value in the adminstrative panel, default applied is *; in this case it's the robot that decides to index your content!

Ok, but how can we set up differents values for our pages?

Setting differents robots values in Magento

There is a solution: we will use the layout structure of our pages: In these layouts, we can reference our block Mage_Page_Block_Html_Head which is responsible for displaying the robots instructions in our page. If we check the block class, it extends Varien_Object (so it's a classic Magento object), and have a method getRobots defined as this:

As you can see, robots values are stored in the _data property, under index 'robots'. So we just have to call setRobots method on your block, and it will update the related _data property, and so our robots values for our page.

Here's an example of layout robots definition:


With this method, we do not have to make an overload. Magento layout allows to define easily our robots preferences. Now we are able to restrict indexation in checkout, do not follow links in customer account, etc.

If you embed these instructions in some reuse module, you can now have your common robots policy set up in 5 min for each of your projects

This configuration will only works for crawlers that take care of the robots instructions. Some of them does not use them and index everything. For these ones, we have to find another way 🙂

How to validate Magento configuration values format?

Magento provides a very easy way to use API to set up configurations values. But really often, in additionnal packages you may develop, expected format is not checked before submitting configuration. You added a text field to allow entereing a webservice URL and can enter only numerics in this field ? Why ?

How to set up a validator for my configuration text field?

This is very easy: we must only add the appropriate css class to our configuration field. All is done in the system.xml file. Take a look at the example: Here’s an example in Magento configuration which validates a field value as an email value:

If we provide an unexpected value, we have an error before submitting post:

Here’s an example of an email format validation for the trans_email/ident_custom1/email configuration value: we must only define <validate> XML node and set up the validation class we want for our field

After rendering, we have the following output:

A new css has been added to our input field. Before submitting, Magento will check this CSS and run the appropriate validation.

It’s fine isn’t it? But how can we define our validator?

Embbeded configurations values validator in Magento

First, let’s look at the embedded validators. They are numerous. You can fiund them in the js/prototype/validation.js file

  • validate-select
  • required-entry
  • validate-number
  • validate-digits
  • validate-digits-range
  • validate-alpha
  • validate-code
  • validate-alphanum
  • validate-street
  • validate-phoneStrict
  • validate-phoneLax
  • validate-fax
  • validate-date
  • validate-email
  • validate-emailSender
  • validate-password
  • validate-admin-password
  • validate-cpassword
  • validate-url
  • validate-clean-url
  • validate-identifier
  • validate-xml-identifier
  • validate-ssn
  • validate-zip
  • validate-zip-international
  • validate-date-au
  • validate-currency-dollar
  • validate-one-required
  • validate-one-required-by-name
  • validate-not-negative-number
  • validate-new-password
  • validate-greater-than-zero
  • validate-zero-or-greater
  • validate-cc-number
  • validate-cc-type-select
  • validate-cc-exp
  • validate-cc-cvn
  • validate-ajax
  • validate-css-length
  • validate-length
  • validate-percents
  • validate-cc-ukss

Very interesting list isn’t it?

Can we use multiples validators for one field?

The answer is yes. If we check the class which convert your system.xml in a pretty form (Mage_Adminhtml_Block_System_Config_Form), this class takes the <validate> field content and appends its value to the CSS class field.

So if you want to add multiples validators to one field, you must separate them by one space

Limitations of validation usage in Magento admin configuration panel

The problem is that we can’t do what we want with the validate XML node:

Only some validators can be used to administrate your configuration values

Yes it’s a shame, but you cannot use all the validators listed above when you set up an administrable configuration value: You can only used those which take one parameter. I let you check which one you can use in admin. The other ones are used in templates and more expected parameters are provided manually

Define its own validator

Damned, my validator is not in the embedded list. I have to define my own validator. No problem, it’s very easy; I’ll take for example what I’ve done for the criteo module MExplained_Criteo (published soon) to validate some Criteo specific variables

Write it’s own validator

Here’s what I’ve done to define my own validators:

First, all these validators must have the following syntax: an identifier, an error message if field value doesn’t validate, and a function which runs the validation.When done, they must be added to global Validation javascript object (loaded by Magento). When javascript is loaded in the page, these validator definitions will be added to the available validation methods and so can be used in submission form if they are defined

Load validator in config admin page

So we just need to load our javascript file in admin configuration page. Very easily with layout:

With that, we have defined our specific validators, loaded them in configuration page and we have provided their usage in our system.xml file. It should work fine 🙂

Just note that you cannot load your new validations methods only for one section or group: if you load js with layout syntax, your new validators can be used in each section / group


Don’t forget to organize correctly your code: if you define some generic validators, perhaps it could be interesting to organize them in one dedicated module to ensure that you can reuse them when you want

This is the client side validation. This does not do the server-side validation. I’ll probably do a little post on this subject in the next few weeks. But with that, we should have the expected submitted data format

Yes I agree with you, these validations are not mandatory. But it improves your administrative panel no? And honestly, how long do you take to write a validator and load it? 5 minutes? 10? Is it comparable to the time spent to resolve a support ticket linked to a wrong configuration value?