ContentType based ID

Topics: Customizing Orchard
Nov 28, 2012 at 12:35 AM

Im looking at having URL's based on a content's ID. Im currently using the basic Content.ID (or whatever it is) in autoroute but the issue is that I want the ID to be per content type and not global.

 

For example, if I have a content type of news and one of blog, I would like the url to be:

http://localhost/news/1

http://localhost/blog/1

and not

http://localhost/news/212

http://localhost/news/220

 

Would this only be possible with a custom module/part and increments everytime new content is created or is there another way? I know I can do it manually through the route section, but that would not be ideal.

 

Thanks

Coordinator
Nov 28, 2012 at 1:03 AM

Sounds like a really strange idea, but yes, you can do that with a custom module.

Nov 28, 2012 at 3:29 AM

How could I get the previous items ID so I could increment it by one for the new ID or can I set the datamigrations to use auto increment on this field and orchard will automatically pass back the generated id?

Coordinator
Nov 28, 2012 at 7:09 AM

Well, that's for you to implement. Auto-increment would probably work, yes.

Dec 27, 2012 at 11:58 PM
Edited Dec 28, 2012 at 12:00 AM

Well I came up with this, though its not a very good way to do it and if you remove the latest content item (say, id 6) and add a new item, it will be 6 and not 7 since the last doesnt contain deleted items.

This is my "protected override DriverResult Editor(ContentTypeIDPart part, IUpdateModel updater, dynamic shapeHelper)" function:

 

 

if (part.ContentID == 0)
{
	int max = 0;
	IEnumerable<ContentTypeIDPart> x = part.ContentItem.ContentManager.List<ContentTypeIDPart>();

	var e = x.GetEnumerator();

	while (e.MoveNext())
	{
		if (e.Current.ContentType.Equals(part.TypeDefinition.Name))
		{
			if (e.Current.ContentID >= max)
			{
				max = e.Current.ContentID;
			}
		}
	}

	part.ContentID = (max + 1);
}

part.ContentType = part.TypeDefinition.Name;

try
{
	updater.TryUpdateModel(part, Prefix, null, null);
}
catch (Exception ex)
{
	Console.WriteLine(ex.ToString());
}

return Editor(part, shapeHelper);

 

Model:

    public class ContentTypeIDPartRecord : ContentPartRecord
    {
        public virtual string ContentType { get; set; }
        public virtual int ContentID { get; set; }
    }

 

I assume I now add Tokens so I can add it to the autoroute?