Search code examples
c#sitecoresitecore7glass-mapper

How to apply standard values to an item created with Glass.Mapper


I create a Sitecore item through the Glass.Mapper like this:

var homeItem = sitecoreContext.GetHomeItem<HomeItem>();

// Create the car item
ICar car = sitecoreService.Create(homeItem.BooksFolder, new Car { Tires = 4, Seats=4});

This works, except the standard values on the Car template are not applied - or if they are they are being immediatetely overwritten by the new Car properties. So if the Car object has a value of null for the Color property, this null is written to the field instead of the "green" value from the standard values on the Car template.

I have looked for a sensible way to do this through Glass.Mapper, but have found nothing. Is there a way to do this through Glass.Mapper?


Solution

  • There is a way to do this, use the override of the Create method that looks like this:

    T Create<T, TK>(TK parent, string newName, Language language = null, bool updateStatistics = true, bool silent = false) where T : class where TK : class;
    

    So your code would look something like this:

    var homeItem = sitecoreContext.GetHomeItem<HomeItem>();
    
    var carName = "Some New Name";
    
    // Create the car item
    // I don't know what the type of BooksFolder is so you would put that in the place of Folder.
    ICar car = sitecoreService.Create<Car, Folder>(homeItem.BooksFolder, carName);
    car.Tires = 4;
    car.Seats = 4;
    
    sitecoreService.Save(car);
    

    We were running into the same issue and this is how we got around it.