Checking the type of a link in Sitecore
Asked Answered
P

2

6

I have a 'General Link' field in one of my pages in Sitecore. This field basically specifies the link of a video file which is used to play a video.

Now, what I am trying to do is, check if the type of this link, whether the user has uploaded a link as an internal link, media or an external link. I need this info as, depending upon the type of the link, I need to perform some actions accordingly.

Is there a way to do check the type of a link in Sitecore?

Potentiality answered 6/2, 2012 at 14:58 Comment(0)
D
21

1st you need to get the field off of your item.

Sitecore.Data.Fields.LinkField field = Sitecore.Context.Item.Fields["FIELD_NAME"];

Then, you can inspect various properties of your field.

bool isInternal = field.IsInternal;
bool isMedia = field.IsMediaLink;
string linkType = field.LinkType;

The various LinkType values are internal, external, media, anchor, mailto, and javascript

Defraud answered 6/2, 2012 at 15:2 Comment(0)
H
11

Let me state something additional please. In your case you want to have some additional action based on linktype. In the sitecore documentation you can find some more info about this. To help you on this see the code underneath:

public static string GetUrl(this Sitecore.Data.Fields.LinkField LinkField) {

        string url = "";

        switch (LinkField.LinkType) {
            case "internal":
            case "external":
            case "mailto":
            case "anchor":
            case "javascript":
                url = LinkField.Url;
                break;
            case "media":
                MediaItem media = new MediaItem(LinkField.TargetItem);
                url = Sitecore.StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(media));
                break;
            case "":
            default:
                break;
        }

        return url;

    }

This way you can get some method up that will always return you the correct url based on the link type. Good luck with it!

Hybris answered 7/2, 2012 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.