Search code examples
orchardcms

Create two separate Alternate for media library picker field in Detail and summary mode of a custom content type


I use Orchard CMS 1.10.1. I have created a custom content type name "Animal" that has a MediaLibraryPicker field. And I have created a projection to show a list of Animals. In this list I want to show Parts_Image_Summary and in Animal Detail mode I want to show Parts_Image_Detail. For this Purpose I created an Alternate Fields.MediaLibraryPicker-Animal.cshtml and Changed its Code from

@Display(BuildDisplay(content, "Summary"))

to

@Display(BuildDisplay(content, "Detail"))

Problem is this alternate effects both Animal Detail mode and Animal Summary mode which I just need this alternate for Animal detail Mode.

Shape tracer doesn't show any alternate name that fits my need. I tried to change the alternate file name to Fields.MediaLibraryPicker-Animal-Detail.cshtml but it didn't work.


Solution

  • Orchard has a lot of field alternates, but these alternates did not include this one, but you can add any new alternate simply by implementing IShapeTableProvider interface as following:

    public class Shapes : IShapeTableProvider {
        public void Discover(ShapeTableBuilder builder) {
            builder.Describe("Fields_MediaLibraryPicker")
               .OnDisplaying(displaying => {
                   ContentItem contentItem = displaying.Shape.ContentItem as ContentItem;
    
                   if (contentItem == null) {
                       return;
                   }
    
                   // [ShapeType]__[ContentType]__[DisplayType] e.g. Fields.MediaLibraryPicker-Animal-Detail
                   displaying.ShapeMetadata.Alternates.Add(EncodeAlternateElement(
                       displaying.ShapeMetadata.Type + "__" +
                       contentItem.ContentType + "__" +
                       displaying.ShapeMetadata.DisplayType));
               });
        }
    
        private string EncodeAlternateElement(string alternateElement) {
            return alternateElement.Replace("-", "__").Replace(".", "_").Replace(" ", "");
        }
    }