API help committing work item updates

Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
Hello,

My company would like to have the activities of a CR auto-populate to High priority if High priority is chosen in the General tab.  I figured it wasn't too hard, and I feel like I'm pretty close to getting it, but I'm definitely missing something.

Would someone mind taking a look at this code and see if they can determine why the commit of the new data doesn't take effect?  Displaying the activity in the console at the end of the script shows that the activity has the priority set as I wanted, but the commit never displays in the activity, even after saving and reloading the form.  No errors in the console after the commit either.

Apologies for the mix of jquery and JS, I'm learning little by little.  The for loop in the first section starts at 1 because the first activity in our templates is just a formatting runbook.  Also, I have tried setting the newData.Activity.Priority as an array before committing, and that didn't seem to get it either.

let workItem = $('span[data-bind="text: view.id"]').html();
$.ajax({
     url: '/api/V3/Projection/GetProjection?id=' + workItem + '&typeProjectionId=4C8F4F06-4C8F-A1B6-C104-          89CFB7B593FA',
     type: 'GET',
     success: function(data) {
          let newData = data;
          let activityCount = newData.Activity.length;
          for (let i = 1; i < activityCount; i++) {
               newData.Activity[i].Priority.HierarchyLevel = 0;
               newData.Activity[i].Priority.HierarchyPath = null;
               newData.Activity[i].Priority.Id = "32ee0157-fdc5-67c4-7971-c6b1fe8dfc66";
               newData.Activity[i].Priority.Name = "High";
          }
          let strData = { "formJson":{ "current": newData, "original": data } };
          // Save Activities as High Priority
          $.ajax({
               type: 'POST',
               url: '/api/V3/Projection/Commit',
               data: JSON.stringify(strData),
               contentType: "application/json",
               dataType: 'json',
               success: function() {
                    console.log('done');
               },
          });
     }
});

Best Answers

Answers

  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    Thanks for the responses.  @Geoff_Ross ;I definitely appreciate that knowledge.  I will continue to update my code with jquery as I learn it.  I didn't know about the viewModel and about the copy using json as you demonstrated.

    I took the suggestions back to my script.  I copied what Geoff sent exactly as shown in his post.  Everything looked as if it was going to work, but the commit didn't take.  I logged out the data and newData variables to see before the commit, and the priority was updated for the "current" json, so I thought that was going to do it.

    @Jeff_Lang ;you're right about the PA issue, I would've definitely run into that pretty quick, so I will certainly need to update my code.  I will be the first to admit I'm probably not doing it right, but when trying to get the form to update directly within the form, I'm not having any luck, and getting json errors.  Perhaps you're saying to just manipulate the form without using the API, which I haven't tried yet.

    I'm using a similar process for updating items from the grid itself, such as directly assigning items from the Team Work view, so it's not the first time I've used the commit API, and I was hoping I could handle this.  At least I didn't make any promises to management.  If you guys have any more suggestions, they're welcome, but I'll definitely keep at it as well, as it can't hurt to keep learning!
  • Geoff_RossGeoff_Ross Cireson Consultant Super IT Monkey ✭✭✭✭✭
    Raymond, are you still hitting the success block of the commit call? If not, do you see any error in Browser Console or WebConsole.log when it fails? 

    I might have something else that could work, let me dig it out.
  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    Yep, all it's doing is logging out "Done" still to let me know that it made it that far, but it is definitely getting there without errors.
  • Geoff_RossGeoff_Ross Cireson Consultant Super IT Monkey ✭✭✭✭✭
    Try this: Take the commit out and replace with the pageForm.save() method. 

    var data = pageForm.viewModel;
    function loopActivities(act) {
        for (var i = 0; i < act.length; i++) {
            act[i].Priority.Id = "32ee0157-fdc5-67c4-7971-c6b1fe8dfc66";
            if (act[i].Activity.length > 0) {
               loopActivities(act[i].Activity
            }
        }
    }
    if (data.Activity.length > 0) { 
        loopActivities(data.Activity}
    }
    
    pageForm.save(function (data) {
        location.reload();
    });

    Again, it only works when you are on the actual WorkItem page, but that is basically the method that gets called when you click apply.
  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    I'm getting an error when it does the pageForm.save that states failure is not a function. 

    I don't know if this helps, but as a test, instead of priority, I changed the description of an activity, using the original script and that worked.  Can it be that the priority field isn't being handled properly in the script?
  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    Also, if I try to change the priority to null instead of a specific Id, that works as well.
  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    Yes, of course!  That was it!  So, just in case down the road anyone else wants to do this, I'm using the script that Geoff posted initially in response to my question and make sure to choose the priority Id that relates to the activity!  Oh, and loop through it for PAs.

    Thanks again for the help!
  • Raymond_DidonatoRaymond_Didonato Customer IT Monkey ✭
    I took another pass on this script because the script worked, but only for editing existing CRs.  My end goal was to have this work while creating a new CR as well.  I think I have it working well in any situation, for maximum user satisfaction :)

    If anyone is interested, here's the current code:

    app.custom.formTasks.add('ChangeRequest', null, function (formObj, viewModel) {
         formObj.boundReady(function () {
              //Get the Priority at page load
              var startPriority = $('div[data-role="Priority"]').val();
              var getPriority = startPriority.Name;
              
              //Watch if the user changes the Priority of the CR
              const observer = new MutationObserver(function (mutations) {
                   mutations.forEach(function (mutation) {
                        if (mutation.target.localName == 'input') {
                             //Find the new priority of the CR
                             var changePriority = $('div[data-role="Priority"]').val();
                             var newPriority = changePriority.Name;
                             //If the new value is different from the starting value, trigger the function
                             if (getPriority != newPriority) {
                                 
                                  //In my environment, I have another script that sets MA fields to required, this clears it in                                    order to apply changes
                                  $('input[required="required"], input[required], div[required]').removeAttr('required');

                                  //Change the priority on the activity forms
                                  convertActivityPriorities(newPriority);
                             }
                        }
                   });
              });

              const pageElement = document.getElementById('main_wrapper');
              observer.observe(pageElement, {
                   attributes: true,
                   subtree: true
              });
         });
    });

    function convertActivityPriorities(newPriority) {
         //Find the Id value for an activity Priority
         var priorityId;
         if (newPriority == 'High') {
              priorityId = 'b2968b97-8f66-ee5e-84ec-f435fa685544';
         } else if (newPriority == 'Medium') {
              priorityId = '5f29e330-5fc0-46fd-715a-5fd2e0980488';
         } else if (newPriority == 'Low') {
              priorityId = '0325c244-387b-d31a-e229-943bfa1924fe';
         }
         var activityCount = pageForm.viewModel.Activity.length;
         for (var i = 1; i < activityCount; i++) {
              //Set the Priority Id on the activities
              pageForm.viewModel.Activity[i].Priority.Id = priorityId;
              //If PA, set the Priority Id for the activities within
              var parallelCheck = pageForm.viewModel.Activity[i].Activity;
              if (parallelCheck) {
                   for (var e = 0; e < parallelCheck.length; e++) {
                        parallelCheck[e].Priority.Id = priorityId;
                   }
              }
         }
         //Apply the changes
         $('button:contains("Apply")').trigger('click');
    }
Sign In or Register to comment.