Dynamics CRM - error publishing entity, role does not exist

This morning I was trying to add a new option to an option set field for a custom entity I had made earlier, however an error dialog popped up which said “The requested record is unavailable or you have insufficient permission to view the record”, even though I’m in a System Administrator role.  Upon downloading the exception details and examining them, the actual error was this:

role With Id = dba45c71-05e2-e311-9210-0050568f0001 Does Not Exist

At one point there were multiple custom roles and multiple forms associated with this entity, configured such that people in an employee role could see one form and people in a manager/admin role could see a different form with more fields, things like that.  Later on this functionality wasn’t required so I deleted all but one of the custom forms and roles, however it turns out that this form still had references to those custom roles.

There wasn’t much information around about this, and all the solutions I could find were like https://community.dynamics.com/crm/f/117/p/73740/135685.aspx referring to just deleting various things like custom forms, which seemed like a pretty weak solution to me.  I searched the database for a form containing a reference to the missing security role:

SELECT  formxml
FROM    FilteredSystemForm
where formxml like ‘%dba45c71-05e2-e311-9210-0050568f0001%‘


This showed that the form’s XML contained the following section right at the end:

<DisplayConditions FallbackForm="true”>
    <Role Id=”{D2A56150-05E2-E311-9210-0050568F0001}” />
    <Role Id=”{DBA45C71-05E2-E311-9210-0050568F0001}” />
    <Role Id=”{DB70F508-654A-DD11-BE40-001E4F1B8E8B}” />
    <Role Id=”{4F7AF508-654A-DD11-BE40-001E4F1B8E8B}” />
</DisplayConditions>


The MSDN documentation for this section (http://msdn.microsoft.com/en-us/library/gg334497.aspx) shows that you can also use an <Everyone> element instead of the <Role> elements, and since I only had one form now it was no longer necessary to deal with security roles.  I tried updating this the Microsoft-approved way with the form editor, but this threw another error at me when I tried to update it to “Everyone” probably again due to the missing security roles.  So my only option was to edit the form directly in the database, which looked something like this (not the full command - don’t copy this):

UPDATE systemformbase
SET formxml = ‘loads of XML ending with <DisplayConditions FallbackForm="true”><Everyone /></DisplayConditions></form>‘
WHERE formid = ‘the form’s guid'


Seriously don’t copy/paste that or you might wreck your form (I really shouldn’t need to say that but you know how people are). Anyway, that solved my problem without needing to delete anything!  Hopefully it helps you solve yours too :)