How do I save a value into a custom field in JIRA programmatically?

enormace picture enormace · Nov 24, 2011 · Viewed 15.5k times · Source

I've spent days trying to find out how to save or update a value into a CustomField programmatically and finally found out how it's done. So I'll make this a question and then answer it as I would have loved to have this question and answer.

There is conflicting documentation on how to save or update a value for a Custom Field in JIRA. I was using:

customField.setCustomFieldValue(CustomField, value);

This does not save the value into the database but it does update the value as far as I can tell. It's only useful if you are using the CustomField further down in a Workflow Post Function transition for example.

I'm using Jira 4.3.2.

How do I persist the the CustomFields value into the JIRA database?

Answer

enormace picture enormace · Nov 25, 2011

Ok, this is how I'm successfully updating and saving the CustomField value into the JIRA db.

Comments welcome...

private void saveValue(MutableIssue issue, String valueToSave, CustomField
        customField) throws FieldLayoutStorageException {

    issue.setCustomFieldValue(customField, valueToSave);

    Map<String, ModifiedValue> modifiedFields = issue.getModifiedFields();

    FieldLayoutItem fieldLayoutItem =
    ComponentManager.getInstance().getFieldLayoutManager().getFieldLayout(issue).getFieldLayoutItem(
            customField);

    DefaultIssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();

    final ModifiedValue modifiedValue = (ModifiedValue) modifiedFields.get(customField.getId());

    customField.updateValue(fieldLayoutItem, issue, modifiedValue, issueChangeHolder);
}