3

Is it possible to cast/convert an IContent to IPublishedContent or a Model's builder model inside a ContentService's hook?

More specifically, I am using the Saving hook as you can see below. Reference for the hook: https://our.umbraco.com/documentation/reference/events/contentservice-events

Problem is that content variable is an IContent type and I can't cast it.

Relevant code of mine which returns variable "question" as null:

  private void ContentService_Saving(Umbraco.Core.Services.IContentService sender, Umbraco.Core.Events.ContentSavingEventArgs e)
    {
        foreach (var content in e.SavedEntities)                         
        {
            var documentType = content.ContentType.Alias;
            var question = content as IPublishedContent;

        }
    }
Antonios Tsimourtos
  • 1,676
  • 1
  • 14
  • 37

3 Answers3

3

You're actually not supposed to be casting between these types. There's a very clear distinction between these two types:

  • IContent is content that is used for editing and saving to the database.
  • IPublishedContent is used to visualize content on the front-end in a fast way.

The IPublishedContent is cached in a special layer (NuCache in Umbraco v8).

When you hook in the Saving event, you aren't doing anything with published items yet, because that step comes after (and it's optional), so you should only work with IContent.

dsbaiz
  • 31
  • 2
1

It would have to be

var question = Umbraco.Web.Composing.Current.UmbracoHelper.Content(content.Id);
Davor Zlotrg
  • 6,020
  • 2
  • 33
  • 51
  • `node` you mean `content` right (according to my example)? However, this could work when an already published item gets saved again. But no ID is returned when a new item is being created and saved for the first time. – Antonios Tsimourtos Jul 03 '19 at 15:03
  • @AntoniosTsimourtos you are right, it should be `content` - I edited an answer. And IPublishedContent only makes sense for published nodes - not the ones that are just created and not published. – Davor Zlotrg Jul 03 '19 at 19:51
  • I see! So, is there a way to cast an IContent Model to a Model's builder model? What is the way to cast it since we are in the Saving hook; which means that node is not published/node doesn't have an ID – Antonios Tsimourtos Jul 04 '19 at 07:50
0

Hi @Antonios Tsimourtos

There is currently no built in way to convert IContent to Model's builder model. Look at this page It does what you are after but it is lot of code https://gist.github.com/jbreuer/dde3605035179c34b7287850c45cb8c9