Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Groovy to find if project exists

-
Contributor
May 1, 2020

What could I use in a Scriptrunner behaviour to find out if a certain project id/key exists in my instance? How would I turn that into code (if comparing against a text custom field)?

1 answer

1 accepted

0 votes
Answer accepted
Lasse Langhorn
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 1, 2020

Hi,

If you have the project key like TEST in a custom field named with ID customfield_11111 then you use something like this below to check if project exists.

package dk.langhornweb

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.ProjectManager

// Get project key from custom field
def projectKey = getFieldById("customfield_11111")
if (projectKey) {
def projectManager = ComponentAccessor.getComponent(ProjectManager)
def project = projectManager.getProjectObjByKey(projectKey)
if (project) {
// Do something with project
} else {
// No project
}
}

Hope this helps

Regards

Lasse Langhorn

-
Contributor
May 4, 2020

I was able to reference your solution successfully

import com.atlassian.jira.bc.JiraServiceContext
import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.bc.issue.search.SearchService

if(!underlyingIssue) {
def TK = getFieldById(getFieldChanged())
def String TKVal = TK.getValue()
def projectManager = ComponentAccessor.getProjectManager()
ProjectService projectService = ComponentAccessor.getComponent(ProjectService.class);
JiraServiceContext jiraServiceContext = new JiraServiceContextImpl(ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser())

if(TKVal.isEmpty())
{
TK.clearError()
} else {
if( projectService.isValidProjectKey( jiraServiceContext, TKVal ) == true )
{
TK.clearError()
} else if (projectManager.getProjectByCurrentKeyIgnoreCase(TKVal) != null) {
TK.setError("Project Key already in use")
} else{
TK.setError("Project Key invalid")
}
}
}

 Many thanks @Lasse Langhorn !

Suggest an answer

Log in or Sign up to answer