Wednesday, April 20, 2011

Lookup Count Related

Just a quick post that I will dive into later after more testing but this is how I am using the CountRelated option to count comments for a blog I am building:

<Field Name="NumComments" ReadOnly="TRUE" Type="Lookup" DisplayName="Comments" CountRelated="TRUE" List="Lists/Comments" ShowField="PostTitle" ID="{Guid Here}" StaticName="NumComments" />

So let's say you have a list called posts for a blog or just about any list will do. I created the field NumComments above. It is a lookup field to the Comments list looking for the field PostTitle. This will actually count the number of comments that have the title of the Blog item in the Comments list in the PostTitle field. This is how the comments field in the OOB blog sites in WSS work.

So another use might be to count the number of times certain keywords or categories show up in a list. The main key is that CountRelated attribute. The rest of the field definition is a standard lookup field. So instead of displaying text, it displays a number which is the count of times the lookup shows up in the selected list. So this field is defined in a parent list and the Lists/Comments in the example would be the child list. ShowField is the name of the field that you are looking up that contains the value you want to count. That is pretty cool!