0
votes

I've got the task of updating a CRM plugin for a system migrating from cm 2013 to 2016. The plugin fails because it tries to set the opportunity state to won, simply by updating the field. And you need to use the WinOpporunityRequest to do so.

The logic is as follows:

  1. When the opportunity is won the plugin executes and runs on the opportunityclose entity
  2. The plugin creates a new custom entity record (project) and updates several other records.
  3. It gets the current opportunity by using the opportunityid of the opportunityclose entity
  4. It updates a field on the opportunity with a reference to the newly created project record.
  5. That update is done through the Update() method.

On 5 it fails because when at 3 it gets the current opportunity it already has the state of won. And if you try to update the record with a new state it fails.

My question is, how can I get the opportunity when acting on the opportunityclose entity and update only the one single field. I do not need to set the state as this is done in the standard CRM flow.

--Edit The line of code that fetches the opportunity:

Xrm.Opportunity currentOpportunityObjectToUpdate = serviceContext.CreateQuery<Xrm.Opportunity>().First(x => x.Id == entityRef.Id);
1

1 Answers

1
votes

The platform allows you to update closed opportunities, I just tried it to verify. What is the error you are getting?

In step #5, make sure you're only sending the attributes you're trying to update (opportunityid and lookup to project). So, when you issue the update, don't use any preexisting opportunity object that you either retrieved or created...doing so sends all attributes that are on the object and the platform will process each attribute as if it were being changed even if the value is unchanged. Instead, create a new opportunity object with just the id and project specified, something like this:

context.AddObject(new Opportunity() { 
    Id = idOfOpportunity,            // you may have to specify id both here...
    OpportunityId = idOfOpportunity, // ...and here, can never remember. Doesn't hurt to specify in both places.
    new_ProjectId = idOfProject
}); 
context.SaveChanges();

If you get stuck, you always have an easy workaround option: take the logic from #4 and move it to an async plugin on create of project (even a workflow should work).