Automating custom field creation in Redmine
-
20-09-2019 - |
Question
I want to write a plugin for redmine that will depend on quite a few custom fields, so I would like to create the custom fields automatically. Ideally within the plugin code, or if not by a script I can run when I install the plugin - I really don't want to have to create 10+ fields through the web interface when I set this up, especially when one is a list with quite a few values.
Can anyone tell me if there are standard ways of doing this?
Also is there a good way to export the custom fields from an existing installation?
Solution
You should use migrate scripts. Put your scripts into #{PLUGIN_ROOT}/db/migrate
and call .create
there. The Redmine sources contain many similar scripts.
For example, the script can have a name: 001_populate_custom_fields.rb
.
Content:
class PopulateCustomFields < ActiveRecord::Migration
def self.up
CustomField.create ...
end
def self.down
end
end
OTHER TIPS
Custom fields essentially are pretty much implemented as a resource (however there is no resource route for custom_fields). I don't see a reason why you shouldn't be able to just use CustomField.create/new to create the fields your plugin needs. Likewise you should be able to just use find() to get all existing custom fields. However, I have to say that I have never done this before and don't know if this is the standard way. But, off the hand, I can't see anything wrong with doing it this way.
As Andriy Lesyuk answered, put your script under #{PLUGIN_ROOT}/db/migrate
and test it by using the command for installing/uninstalling your plugin.
For installing the plugin use the command:
rake redmine:plugins:migrate
and for uninstalling it:
rake redmine:plugins:migrate NAME=<your plugin name> VERSION=0
Check the official documentation for further details.
For example, the script 001_populate_custom_fields.rb
could be something like:
class PopulateCustomFields < ActiveRecord::Migration
# method called when installing the plugin
def self.up
if CustomField.find_by_name('A New Custom Field').nil?
CustomField.create(name: 'A New Custom Field', field_format: 'text')
end
end
# method called when uninstalling the plugin
def self.down
CustomField.find_by_name('A New Custom Field').delete unless CustomField.find_by_name('A New Custom Field').nil?
end
end
This will create/remove the custom field "A New Custom Field" of type "text", after checking its existence from the redmine database table custom_fields.