Search code examples
javajirajira-pluginatlassian-plugin-sdk

How to update custom field in jira 7+ using java


Answers to this question are outdated or incomplete on all the sources that I checked.

Here are some examples:

Delete issue in JIRA using Java

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

JIRA creating issue using java

Automating custom field value change in JIRA

Jira: How to obtain the previous value for a custom field in a custom IssueEventListener

CustomFieldManager is not getting the custom field after modifying the custom field name using REST api in jira

I don't have enough reputation to comment on any of theese questions. But I have an answer.


Solution

  • So here is my resolution:

    CustomField csUserField = ComponentAccessor.getCustomFieldManager().getCustomFieldObjectByName(fieldName);
    IssueService issueService = ComponentAccessor.getIssueService();
    IssueInputParameters issueInputParameters = issueService.newIssueInputParameters();
    issueInputParameters.addCustomFieldValue(csUserField.getId(), value_string);
    issueInputParameters.setSkipScreenCheck(true);
    issueInputParameters.setRetainExistingValuesWhenParameterNotProvided(true, true);
    UpdateValidationResult updateValidationResult = issueService.validateUpdate(user, issue.getId(), issueInputParameters);  
    if (updateValidationResult.isValid())
    {
        IssueResult updateResult = issueService.update(user, updateValidationResult);
        if (!updateResult.isValid())
        {
            log.warn("ISSUE has NOT been updated. Errors: {}\n", updateResult.getErrorCollection().toString());
        }
        else
        {
            log.warn("ISSUE has been updated.\n");
        }
    }
    else
    {
        log.warn("ISSUE has NOT been updated. Errors: {}\n", updateResult.getErrorCollection().toString());
    }