Search code examples
episerverepiserver-8

Deleting block from a ContentArea


I want to delete block with broken links from my page. Fx we use EPi Server Commerce, and sometime a product is deleted from the PIM in Commerce and I need to remove all the Blocks that had that product referred.

But something is 'wonky'...

Some blocks sometimes still exists after I've tried to delete them. If I put a new block in the ContentArea, it seems to remove the old values and the ContentArea is fine again. It's like EPi server does not see my change as a change and doesnt publish anything.

        private void CleanNonExistingBlocks(PageData page)
    {
        page = page.CreateWritableClone();
        var type = page.GetType();
        var props = type.GetProperties();
        bool isPageDirty = false;
        foreach (var propertyInfo in props)
        {
            if (propertyInfo.PropertyType != typeof(ContentArea))
                continue;

            ContentArea value = propertyInfo.GetValue(page, null) as ContentArea;
            if (value == null)
                continue;
            List<ContentAreaItem> list = value.Items.ToList();
            bool isListDirty = false;
            foreach (var contentAreaItem in list.ToList())
            {
                IContent found;
                if (_contentRepository.TryGet<IContent>(contentAreaItem.ContentLink, out found))
                    continue;

                isPageDirty = true;
                isListDirty = true;
                list.RemoveAll(c => c.Equals(contentAreaItem));

            }
            if (isListDirty)
            {
                value.Items.Clear();
                foreach (ContentAreaItem contentAreaItem in list)
                    value.Items.Add(contentAreaItem);
                propertyInfo.SetValue(page, value);
            }
        }
        if (isPageDirty)
        {
            _contentRepository.Save(page, SaveAction.Publish, AccessLevel.NoAccess);
            _outputMessages.Add(page.Name + " - ");
        }
    }

Solution

  • The problem is you are using .NET Reflection API:s and not EPiServers API. See this questions accepted answer for an example of how to work with ContentArea in code:

    EpiServer - Add block to a content area programmatically