Question

In the Developer Section of Umbraco 6.1.6 there is a Relation Types node.

Can anybody explain what Relation Types are and if they have a practical application. I have seen some documentation but am still unsure as to why I might need to use them.

Are they still relevant in v6 and v7?

Was it helpful?

Solution

I've recently starting documenting the Relations Service which should provide some insight into what you can do with it. I use it occasionally to maintain relations between nodes in the content tree.

If you ever copy a node in Umbraco you get the option to relate the new node to the original which uses a relation type called "Relate Document On Copy". As an example, with the relation in place you can then hook into events such as the Save event and whenever the parent is updated you could also update the related child node(s). This technique is sometimes used in multi-language sites that want content synchronised across each language.

The following is an abbreviated example from a recent project I am working in which a recurring event may be created. We need to know the first event in the series and also all subsequent occurrences of the event (the children).

  public class Events : ApplicationEventHandler
  {
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
      ContentService.Saved += ContentServiceSaved;
    }

    private void ContentServiceSaved(IContentService sender, SaveEventArgs<IContent> e)
    {
        var rs = ApplicationContext.Current.Services.RelationService;
        var relationType = rs.GetRelationTypeByAlias("repeatedEventOccurence");

        foreach (IContent content in e.SavedEntities)
        {
            var occurences = rs.GetByParentId(content.Id).Where(r => r.RelationType.Alias == "repeatedEventOccurence");
            bool exists = false;

            foreach (var doc in occurences.Select(o => sender.GetById(o.ChildId)))
            {
                // Check if there is already an occurence of this event with a matching date
            }

            if (!exists)
            {
                var newDoc = sender.Copy(content, eventsDoc.Id, true, User.GetCurrent().Id);

                // Set any properties you need to on the new node
                ...

                rs.Relate(content, newDoc, relationType);
            }       
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top