How do I emulate Content Editor's Remove Links option when deleting an item?
I have a set of items which have a Treelist field that references media items in the Media Library. If I delete a media item which is referenced by another item, I get the "Broken L开发者_JAVA技巧inks" dialog box which gives me the option to Remove Links, Link to Another Item, or just leave the broken links.
What API/code is being called when I select Remove Links? I would like to perform this same action programmatically in the code-behind.
For context, we are allowing our advertising members to upload images and manipulate their library of images (through a custom web interface). So when someone deletes an image from their set, obviously we don't want to leave broken links to these Media Library items.
That would be the Link Database. You can utilize it before you delete the item to find referrers:
Sitecore.Globals.LinkDatabase.GetReferrers(item)
The returned ItemLink objects contain the item and field where the item you are deleting is referenced. Use the appropriate Field class to remove the reference.
Though you may think the RemoveLinks
or RemoveReferences
method on the LinkDatabase will do what you're looking for, it's actually just removing links/references from the Link Database itself.
EDIT:
A little Reflector work comes to a more complete solution... if you use the FieldTypeManager
factory to get the field's CustomField
, you can call RemoveLink(ItemLink)
on the field.
Field field = item.Fields[brokenField];
CustomField field2 = FieldTypeManager.GetField(field);
item.Editing.BeginEdit();
field2.RemoveLink(itemLink);
item.Editing.EndEdit();
This is untested code, found by referencing Sitecore.Shell.Applications.Links.EditLinksForm
精彩评论