Forums

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

How Can I Add scope for Specific Project

Vitheya Monikha June 13, 2025

Hi ,

 

How can I set scope for a specific project? In case you haven't seen the code snippets, I've sent them again. Please take a look at them

UI Code 

 const onSubmit = async (data=> {
      var bodyData;
      setIsLoading(true)
      const folderExists = tree.some(folder => folder.value === data.folderName || folder.value === `${data.folderName}(${parentFolderName})`);
      if (folderExists) {
         setIsLoading(false)
         setFlagTitle('Failure!');
         setFlagMessage('Error: Folder name already exists');
         addFlag();
         return;
      }
      console.log("ParentfoldernameID.........."projectId)
      if (parentFolderName === 'Test Repository') {
         console.log("ParentfoldernameID.........."projectId)

         bodyData = {
            name: data.folderName,
            fieldId: testCaseFieldId,
            projectKey: projectKey,
            projectId: projectId
           
         }
         console.log("bodyDataID.........."projectId)
      }
      else {
         console.log("else.........."projectId)
         bodyData = {
            name: `${data.folderName}(${parentFolderName})`,
            fieldId: testCaseFieldId,
            projectKey: projectKey,
            projectId: projectId
           
         }
         console.log("projectid.........."projectId)
      }

      console.log("Data..."bodyData)
      try {
         const response = await invoke('addOptionToCustomField'bodyData); // API call to get projects
         console.log("comp Response...."response)
         if (response.options[0].id) {
            setIsLoading(false)
            setFlagTitle("Success!")
            setFlagMessage('Folder created successfully')
            setIsOpen(false)
            setShowParentDrp(false);
            reset();
            addFlag();
            setTree([])
            setFolderLoader(true)
            getUpdatedComponentList()
         }

      } catch (error) {
         setIsLoading(false)
         setFlagTitle('Failure!')
         setFlagMessage(`Error while creating folder${error}`)
         addFlag();
         return [];
      }
   }


Backend Code

 

resolver.define("addOptionToCustomField"async({payload}) => {
  console.log("addOptionToCustomField")
  const { fieldIdnameprojectKey } = payload

  console.log("projectkey.........",projectKey)
  try{
    console.log("Payload to create options..."fieldId)
    const contextResponse = await api.asApp().requestJira(route`/rest/api/3/field/${fieldId}/context`, {
      method: "GET",
      headers: { "Accept": "application/json" },
    });
    const contextData = await contextResponse.json();
    console.log("contextData......"contextData)
    const targetContext  = contextData.values.find(ctx => ctx.name === projectKey);
   
    const optionData = [{ value: name }];
    console.log("Option Data........"optionData)
    var res = await api.asApp().requestJira(route`/rest/api/3/field/${fieldId}/context/${targetContext}/option`, {
        method: "POST",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
        body: JSON.stringify({options: optionData}),
    });
      const data = await res.json()
      console.log(`✅ Dropdown options added for ${fieldId}!...`data);
      return data
  }
  catch(error){
    return {"code": 2000"message": "Error while creating folder"}
  }

});

2 answers

0 votes
Vitheya Monikha June 18, 2025

Hi,

 

 

As per your suggestion, I have changed the code, but the project ID is not available in the context data. I would like to know how to add my project ID to it. I have also added the context data JSON as below.

 

Could you please let me know how to add projectID to the context data JSON?

 

This is the backend code 

 

resolver.define("addOptionToCustomField", async ({ payload }) => {
  console.log("addOptionToCustomField")
  const { fieldId, name, projectId } = payload

  console.log("projectkey.........", projectId)
  try {
    console.log("Payload to create options...", fieldId)
    const contextResponse = await api.asApp().requestJira(route`/rest/api/3/field/${fieldId}/context`, {
      method: "GET",
      headers: { "Accept": "application/json" },
    });
    const contextData = await contextResponse.json();
    console.log("contextData......", contextData)
  console.log("payload.projectId.........", projectId)
    const targetContext = contextData.values.find(ctx =>
      ctx.projectIds && ctx.projectIds.includes(projectId)
    );
    console.log("targetContext........", targetContext)
    const optionData = [{ value: name }];
    console.log("Option Data........", optionData)
    var res = await api.asApp().requestJira(route`/rest/api/3/field/${fieldId}/context/${targetContext.id}/option`, {
      method: "POST",
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ options: optionData }),
    });
    const data = await res.json()
    console.log(`✅ Dropdown options added for ${fieldId}!...`, data);
    return data
  }
  catch (error) {
    return { "code": 2000, "message": "Error while creating folder" }
  }

});

 

Example log

contextData...... {
maxResults: 50,
startAt: 0,
total: 1,
isLast: true,
values: [
{
id: '12823',
name: 'Default Configuration Scheme for Folders',
description: 'Default configuration scheme generated by Jira',
isGlobalContext: true,
isAnyIssueType: true
}
]
}

 

0 votes
Tuncay Senturk _Snapbytes_
Community Champion
June 13, 2025

Hi @Vitheya Monikha 

I am not sure if I get your question right but here are my two cents on this.

To set the scope of a custom field to a specific project using your Forge backend function, you need to create (or find if there is) field context that is scoped to the project, and then add the option to that context.

const targetContext = contextData.values.find(ctx => ctx.name === projectKey);

you are using the above code to find but it is IMO incorrect as the project name may not be equal to the projectKey. The below would be a better approach

const targetContext = contextData.values.find(ctx =>
ctx.projectIds && ctx.projectIds.includes(payload.projectId)
);

Please console log to see what data it has and correct the code accordingly.

Also you need to update the rest (targetContext -> targetContext.id) as the below. targetContext is an object not the ID itself.

var res = await api.asApp().requestJira(route`/rest/api/3/field/${fieldId}/context/${targetContext.id}/option`, {

if no such content exists (targetContext is undefined) you'll need to create a new field context scoped to the project.

POST /rest/api/3/field/${fieldId}/context

Then use the new context ID to post the options.

I hope that helps

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events