Recently we came across a scenario where we were assigning CreatedBy and ModifiedBy field of the record that was created by plugin dynamically based on the data of the record that was getting created by plugin.
Let us say, my Contact entity that has field “new_createdby”, ”new_modifiedby” and its records are getting created by plugin. In our scenario if user wants to set “createdby/modifiedby” field dynamically based on the new_createdby/new_modifiedby field value while the records get created through plugin, then in that case below code will help you up in assigning createdby/modifiedby for the record dynamically based on the particular field value.
//get entity record for which plugin was fired Entity _target = (Entity)pluginExecutionContext.InputParameters["Target"]; //check if portaluser name is to be obtained from custom createby or from custom modifiedby if (pluginExecutionContext.MessageName.ToUpper() == "CREATE") { contactid = _target.Attributes.Contains("new_createdby") ? _target.GetAttributeValue<EntityReference>("new_createdby").Id : Guid.Empty; } else { contactid = _target.Attributes.Contains("new_modifiedby") ? _target.GetAttributeValue<EntityReference>("new_modifiedby").Id : Guid.Empty; } //retrieve contact fullname from contactid var _contact = context.CreateQuery("contact").Where(c => c.GetAttributeValue<Guid>("contactid").Equals(contactid)).FirstOrDefault(); if (_contact != null) { if (_contact.Attributes.Contains("fullname")) { fullname = _contact.GetAttributeValue<string>("fullname"); } //retrieve Systemuser that has same name as that of new_portalcreatedby/ //new_portalmodifiedby Entity _user = context.CreateQuery("systemuser").Where(e => e.GetAttributeValue<string>("fullname").Equals(fullname)).FirstOrDefault(); if (_user != null) { //check if we need to update createdby or modifiedby if (pluginExecutionContext.MessageName.ToUpper() == "CREATE") { _target["createdby"] = _user.ToEntityReference(); } else { _target["modifiedby"] = _user.ToEntityReference(); } //assign new target to plugin executioncontext pluginExecutionContext.InputParameters["Target"] = _target; }
This will help you to change createdby/modifiedby field at runtime in plugin.
Planning to Move to Cloud from Dynamics CRM On-Premises? We can help you!
Hello , I have tried to register my plugin in both pre validation & pre operation . but it dint work. can advice on this
We tried the same by registering the plugin on PreOperation and it is working.