So now you have your tables installed in your setup scripts. Now you want to insert some data. This can be dummy data for the user, some default values for attributes, or populated data for items such as geographic locations. It is done via install scripts as well. Data, however, is located in a slightly different place.
It is located in the /data/ folder inside your module.
All other syntax, setup, and other points are the same. Inside the /data/ folder, you will still put a folder with the same name as the setup node in your config xml, (see Part 2). You will still use a similar structure as the installation files, (Part 2). The naming convention with version numbers is also the same (Part 1).
Let’s put together a quick installation script.
1 2 3 4 5 6 7 8 9 10 |
<?php // app/code/local/Namespace/Modulename/data/modulename_setup/data-install-1.0.php $installer = $this; $values = array('one', 'two', 'three'); foreach($values as $value) { Mage::getModel('modulename/content')->setValue($value)->save(); } |
Pretty straightforward.
Use the standard Magento Abstract Factory pattern when inserting data into the database. If a set of data is very large, chances are it might crash Magento. This is especially if you don’t have enough memory allocated to php, or if you don’t set your timeout high enough for script execution. If this is the case, use a sql file instead. Sql files are faster and don’t need to go through all the abstraction layers to get where it needs to go.
So instead of using data-install-1.0.php, you would use data-install-1.0.sql. Inside the sql file would just be your queries without any abstraction.
1 2 3 4 |
# app/code/local/Namespace/Modulename/data/modulename_setup/data-install-1.0.sql INSERT INTO my_table (id, value) VALUES (1, 'one'); # etc... |
The same procedures go with upgrades as well.
The core_resource
table with have a version and a data_version column. This will let you know what version of your data you currently have installed.
Now go and install some data!
Please be aware that using .sql files has a number of downsides.
* The table name prefix that can be specified during an installation of Magento can’t be used in SQL scripts
* Any configuration rewrites for table names won’t be applied
* No observers defined for table name lookups will be triggered
Because of this the core does not use *.sql setup scripts and the feature should be considered deprecated. Only use *.sql setup scripts if the module will never be distributed.
Thanks for the feedback. I will update the article accordingly.