Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute Url for internal Links with Glass Mapper for Sitecore

My item template has a field for a General Link and is representing by the following class:

[SitecoreType]
public class MenuLink
{
    [SitecoreField(FieldName = "Link")]
    public virtual Link Link { get; set; }
}

Now my link field contains external and internal links (links pointing to other items). Is it possible to configure Glass Mapper that the Url Property of the Link contains the absolute url (like AlwaysIncludeServerUrl=true)? And also that is used the site resolving (SiteResolving=true)?

Basically I would like to give the Link property an UrlOptions configuration.

I'm using Sitecore 7.1 with Glass.Mapper.Sc 3.1.2.18.

like image 864
Kevin Brechbühl Avatar asked Jan 19 '14 15:01

Kevin Brechbühl


2 Answers

Kevin

Please download release 3.1.6 I have added the UrlOptions property to the SitecoreFieldAttribute class. You should be able for force the server path like so:

[SitecoreField(UrlOptions=SitecoreInfoUrlOptions.AlwaysIncludeServerUrl)]
public virtual Link MyLink{get;set;}

You can also added other options by piping the flags:

[SitecoreField(UrlOptions=SitecoreInfoUrlOptions.AlwaysIncludeServerUrl|SitecoreInfoUrlOptions.LanguageEmbeddingNever)]
public virtual Link MyLink{get;set;}
like image 92
Michael Edwards Avatar answered Oct 31 '22 13:10

Michael Edwards


Add this extension method to your solution:

using Sitecore;
using Sitecore.Links;
using Glass.Mapper.Sc.Fields;

public static class LinkExtensions
{
    public static string GetLinkUrl(this Link link, ISitecoreContext sitecoreContext = null)
    {
        if (link != null)
        {
            if (link.Type == LinkType.External || link.Type == LinkType.Media)
            {
                return link.Url;
            }
            else if (link.Type == LinkType.Internal)
            {
                var target = (sitecoreContext ?? new SitecoreContext()).Database.GetItem(new ID(link.TargetId));

                var urlOptions = Sitecore.Links.UrlOptions.DefaultOptions;
                urlOptions.AlwaysIncludeServerUrl = true;
                urlOptions.SiteResolving = true;

                return LinkManager.GetItemUrl(target, urlOptions);
            }
        }

        return string.Empty;
    }
}

Then, assuming you have this model:

[SitecoreType]
public class MenuLink
{
    [SitecoreField(FieldName = "Link")]
    public virtual Link Link { get; set; }
}

You can get the URL like this:

model.Link.GetLinkUrl();
like image 41
Ruud van Falier Avatar answered Oct 31 '22 11:10

Ruud van Falier