Groovy script to set previous DateTime Customfield Value

HI @Jamie Echlin [Adaptavist],

                                           Can you help me with a groovy script to set previous customfield value based on change History for a Date Time Custom field ?

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.issue.changehistory.ChangeHistory;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.user.ApplicationUsers;
import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.user.util.UserUtil;
import com.atlassian.jira.web.bean.PagerFilter;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.issuetype.IssueType;
import com.atlassian.jira.exception.CreateException;
import com.atlassian.jira.user.DelegatingApplicationUser;
import com.atlassian.jira.issue.customfields.option.Option;
import com.atlassian.jira.issue.customfields.option.Options;
import com.atlassian.jira.issue.fields.config.FieldConfig;
import java.util.Collection;
import java.util.List;
import java.lang.Object;
import org.apache.log4j.Category;
import com.atlassian.jira.issue.ModifiedValue;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import com.atlassian.jira.util.ImportUtils;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import com.atlassian.jira.issue.fields.layout.field.*;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.ModifiedValue as ModifiedValue;
import com.atlassian.jira.issue.customfields.manager.OptionsManager as OptionsManager;
import com.atlassian.jira.issue.customfields.option.*;
import com.atlassian.jira.issue.changehistory.*;
import com.atlassian.jira.issue.*;
import com.atlassian.jira.issue.history.ChangeLogUtils;
import org.apache.log4j.Category as Category;
import org.apache.log4j.Level as Level;
class RevertCustomField
{
    Category log = Category.getInstance("com.onresolve.jira.groovy.GroovyService");
    SearchService searchService = ComponentAccessor.getComponent(SearchService.class);
    IssueManager issueManager = ComponentAccessor.getIssueManager();
	CustomFieldManager cfm = ComponentAccessor.getCustomFieldManager();
	ProjectManager projectManager = ComponentAccessor.getProjectManager();
	IssueFactory issueFactory = ComponentAccessor.getIssueFactory();
    MutableIssue mIssue = issueFactory.getIssue();UserUtil userUtil = ComponentAccessor.getUserUtil();
    
    def revertCustomFieldValues(String jql, String cft)
    {
        def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
        SearchService.ParseResult parseResult =  searchService.parseQuery(user, jql);
		List<Issue> issues = null;
        if (parseResult.isValid()) 
        {
            def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
    		issues = (List <Issue>) searchResult.issues.collect {issueManager.getIssueObject(it.id)}
    		for (Issue issue  : issues)
            {
        
				ChangeHistoryManager changeHistoryManager = ComponentAccessor.getChangeHistoryManager();            
				List<ChangeItemBean> ChHistory =  changeHistoryManager.getChangeItemsForField(issue, cft); 
				
				if (cft == "CAB Ticket Number" || cft == "Product ID" || cft == "Release Plan")
				{
					if (!ChHistory.isEmpty()) 
					{
						CustomField tgtfield = cfm.getCustomFieldObjectByName(cft);
						FieldLayout layout = ComponentAccessor.getFieldLayoutManager().getFieldLayout(issue);
						FieldLayoutItem fieldLayoutItem = layout.getFieldLayoutItem(tgtfield);
						DefaultIssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();
						ChangeItemBean assigneeChItemBean = ChHistory.get(ChHistory.size() - 1);
						String x = assigneeChItemBean.getFromString(); 
						mIssue.setCustomFieldValue(tgtfield,x);
						Map<String, ModifiedValue> modifiedFields = mIssue.getModifiedFields();
						final ModifiedValue modifiedValue = (ModifiedValue) modifiedFields.get(tgtfield.getId());
						tgtfield.updateValue(fieldLayoutItem, issue, modifiedValue, issueChangeHolder);
						ChangeLogUtils.createChangeGroup(user,issue,issue,issueChangeHolder.getChangeItems(),true);	    
					}
				}	
         	}	
		}
    }
    
    
    
}
def obj = new RevertCustomField();
//String testSelect = obj.revertCustomFieldValues("project = CHAN" , "Custom Select List"); 
String testURL = obj.revertCustomFieldValues("project = ENGRTEST" , "Release Plan");

The above code works fine for URL field. I need to implement the same for Date Time Custom Field

Thank You

Chander

5 answers

0 vote
Steven Behnke Community Champion Nov 04, 2015

It might be better if you simply state your use-case simply, I'm not sure how this code you pasted here applies to the concept you're looking for...

@Steven Behnke The use case is setting DateTime Custom field to its previous value. Say End Time is a custom field 1. First Value set was "x" 2. It was later modified as "y" 3. Need to change it back to x. Hope this is simple enough now.

0 vote

You need to go through the previous change items for that field and set the value to the n - 1 th change. I'm not sure why you have a JQL search here... as Steven said, there is much more code there than what your requirements state.

Actually, what is the piece of code to set Date Time field ? I tried with issue.setCustomFieldValue() and issue.store() and could not succeed.

that should work if it's a post-function and it's the first post-function. But as Steve said, the context here is all important.

0 vote
Steven Behnke Community Champion Nov 09, 2015

Just to confirm, you're trying to make this happen during Issue Edits? Or are you using this during Workflow Transitions? I usually have to put my mindset in the right mode depending on how we'd be calling this script. Again, I'm just not sure what I'm looking with your large script either. Jamie's example is great though, the change history is stored essentially as a list so technically we can peer into the past by one edit to grab that value for our usage.

The context here is running the script via script console and not workflow transitions or post functions, its only one time execution to bring back the field values as there was a mess up during issue type and workflow scheme changes of a project

Suggest an answer

Log in or Sign up to answer
How to earn badges on the Atlassian Community

How to earn badges on the Atlassian Community

Badges are a great way to show off community activity, whether you’re a newbie or a Champion.

Learn more
Community showcase
Published Thursday in Jira

5 ways you can make the most of Jira Software and Bitbucket Cloud

As part of the Bitbucket product team I'm always interested in better understanding what kind of impact the use of our tools have on the way you work. In a recent study we conducted of software devel...

76 views 0 5
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you