Skip to main content

Capture and Handle event when one entity record is attached through a Many to Many relationship - MS CRM 4

If you have already dug up too much about trying to capture the event when an entity record in MS CRM is attached ~ linked to a record in many to many relationship.


For example, if you have two entities : Supplier and Company in MS CRM where a supplier can do business with many companies and at the same time a Company can order stuff from many suppliers. What if you want to send some notification whenever a new supplier or an existing supplier is linked to a company; similarly you may want to send a notification when a Supplier signs a deal with 2-3 companies and gets linked to those.


Some experts from MS CRM fraternity have suggested some ways to over ride this limitation of MS CRM that it does not expose any event for the above mentioned scenario, below is one of the examples:  
http://ayazahmad.wordpress.com/2009/07/23/event-on-many-to-many-relationship-nn-in-crm-4/

But making changes to the default plugin model of MS CRM to add Associate or Disassociate event is not so easy and simple while going from another approach : Javascript can save your day and you can capture events when records are linked or unlinked into a many to many relationship.
-----------------------------------------------------------------------------------
Here's how to carry this out: action begins :

1. As you can see, first step in javascript approach is to get the id of the IFRAME element that shows the many to many relationship associated view which in this case is Accounts. As you can see below, you can get it by doing a F12, and clicking on the border of the iframe: areanew_new_supplier_accountFrame



2. Then you need to bubble the event when a record is linked in m-m rel. which is the Add Button. For that you need the id of the button, do an F12 to bring the developer toolbar, click on and pick the mouse pointer under HTML tab in the bar and click on the Add Existing Account button, if will show you the html tags behind and and you can see the id here : _MBtoplocAssocObjlnewnewsupplieraccount1 as shown in the blue line in the image.





Also you will need the id of the remove button, you may have this button on the main toolbar of the associated view as shown, or you may find it under More Actions menu with sub-menu label "Remove". Find the id of that button or sub menu using the same F12 method, it has a  very long string as id as can be seen below.




 Now go to the Form load script of the entity form, on form load, and add a function for capturing the readystatechange event because we want to bubble ~ over ride the on click event of the add/remove link buttons  so that we can push our own logic.

Things to notice in the following code :
1. Overriding Add existing click button is straight forward, attach an onclick event

2. Since Remove is a sub option under the More Actions menu, I fould it could not be overridden the same above way, so I had tweaked it's Action property, and appended one statement after the default Action, this extra statement is the function call.

function InitializeIFrameEvents(Iframe) {
  Iframe.onreadystatechange = function IframeButtonEvent() {
    if (Iframe.readyState == 'complete') { 
      var iFrame = frames[window.event.srcElement.id];

          if(Iframe.contentWindow.document.getElementById(' _MBtoplocAssocObjlnewnewsupplieraccount1 ')!=null) 
{ Iframe.contentWindow.document.getElementById(' _MBtoplocAssocObjlnewnewsupplieraccount1 ').attachEvent( "onclick" ,onLinkAdd); }    
         if(Iframe.contentWindow.document.getElementById(' _MIdoActionExcrmGrid....very long id of the remove sub option from more actions menu ')!=null) 
       {         
        removeButton=Iframe.contentWindow.document.getElementById('_MIdoActionExcrmGrid....very long id of the remove sub option from more actions menu');
        removeButton.action=" doActionEx('crmGrid', '10047', top.crmFormSubmit.crmFormSubmitId.value, 'disassociate', top.crmFormSubmit.crmFormSubmitObjectType.value, 'tab=areanew_new_supplier_account&associationName=new_new_supplier_account&roleOrd=2');   window.parent.crmForm.  onLinkRemoved();";
       }

    }
  }
}





InitializeIFrameEvents(document.getElementById(' areanew_new_supplier_accountFrame '));


// Here is the javascript handler for Add Existing button 


function onLinkAdd()  

   alert(' link added'); 
   //  you can write your own code here , maintain a Counter field on form that keeps the number of records linked in this m2m relationship, this can help in situation when you want to send some email on each record linked
}


// And this function is for the remove sub option click


function onLinkRemoved()  

   alert(' link removed'); 
  // you can reset the counter that will maintain the number of linked records
}

And there you go, you can now do whatever you want on the add and remove events, going more advanced, you will want to apply your own filter as to allow only certain records example Accounts with City London to be linked while restrict the other accounts. As you know default MS CRM lookup do not allow you this functionality, to do this, you will have to tweak the method that runs when you link records, and add your condition logic over there, I will explain that example in my next post.

Comments

Unknown said…
As for me it is better to do it with plugins...
hero said…
The only advantage here is you don't have to make changes into plugin model and some entries in the CRM table.
Unknown said…
Nice post ,thanks for sharing .
Dynamics CRM Developers
This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It?s the old what goes around comes around routine. Did you acquired lots of links and I see lots of trackbacks??
Dynamics training
Colby said…
Smart stuff. I agree with you 100%!
best gadget reviews
Anonymous said…
Great information of on the Microsoft CRM. But you will be needing a developer to design custom plug-ins. We offer the best Microsoft dynamic CRM development. Take a look.
Jack said…

Managed IT Services provider based in California. We offer dependable & transparent services that focus on maintenance & innovation.
Jack said…
Dynamics 365 Partner break down silos created by traditional ERP and CRM allowing you to manage your customers, operations and business better.
Ravi said…
Excellent post, Thanks for sharing this.

Learn more about CSPO Certification and also many other courses to get the best knowledge.
MNK said…
Interesting blog post...

Regards,
BroadMind - IELTS coaching in Chennai
Alia parker said…
Always check with your chosen printing service for their specific requirements to guarantee that your business cards meet their guidelines. dimension printing

Popular posts from this blog

CRM 2011 Useful JavaScript tidbits

http://www.powerobjects.com/blog/2011/01/14/crm-2011-useful-javascript-tidbits/ Get the value from a CRM field var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ; Set the value of a CRM field Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’); Hide/Show a tab/section Xrm.Page.ui.tabs.get(5).SetVisible(false); Xrm.Page.ui.tabs.get(5).SetVisible(true); Call the onchange event of a field Xrm.Page.getAttribute(“CRMFieldSchemaName”).fireOnChange(); Get the selected value of picklist Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text; Set the requirement level Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”); Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”); Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”); Set the focus to a field Xrm.Page.getControl(“CRMFieldSchemaName”).setFocus(true); Stop an on save event event.returnValue = false; Return array

Abort event through plugins

Suppose you are writing a pre -event plugin in which you compare to  old and new values and on certain condition would like to cancel the Save or  Update and stop the execution, it was simple in CRM 3 with an Abort() method while in CRM 4, you have to manually raise and throw a  Invalid-Plugin-Exception, while this gives a dirty error message on your MSCRM screen, you can make it better by entering you own Message explaining why the record could not be saved: throw new InvalidPluginExecutionException("Execution has been stopped due to this reason");

Using MS CRM Calendar in your custom ASP .NET pages *** Not fully Supported Customisations ***

Hi, Have you been creating custom pages in line with MS CRM for creating , viewing and updating entity records ? Have you placed controls such as Date picker Lookup on your custom page and have tried in vein to make those look like MS CRM ? I found a way to use the same MS CRM calendar control as it appears in the application... For getting this calendar on your asp .net page, follow the steps below: 1) Create a copy of the date.js javascript file located in your-server/crmsite-folder/_static/_controls/datetime folder, give the copy some name like date_myapp.js. 2) Open the following .js files from different sub folders in side the  your-server/crmsite-folder/_static      folder :       Global.js       encodedecode.js       xmlutil.js       util.js       remotecommand.js              Copy and whole content of each file one by one and keep pasting the same to the end of your date_myapp.js file. 3) Now open any CRM entity record page, for example a new Account crea