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

2

6

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?

Krilov answered 31/10, 2014 at 11:52 Comment(0)
G
5

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.

Grating answered 22/1, 2015 at 17:28 Comment(2)
Works perfectly! I guess it makes some sense that when you create a new item from an object, you get exactly what is in that object with no defaults, but when you just create it from a name you get an item with standard values applied.Frazer
@T.J.Kjaer I'd have to disagree this "makes sense" - what would make sense is to have a properly named create method indicating whether standard values would be applied or not :)Presentment
D
1

You could reset the fields you want back to its standard values by calling Sitecore's Reset() method wrapped in the EditContext.

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

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

using(new EditContext())
{
    car.Fields["Color"].Reset();
}

See http://firebreaksice.com/how-to-reset-individual-sitecore-fields-to-standard-values/

Decrepit answered 7/1, 2016 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.