Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
T.J.Kjaer Avatar asked Oct 31 '14 11:10

T.J.Kjaer


2 Answers

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.

like image 141
Nick Cipollina Avatar answered Oct 21 '22 20:10

Nick Cipollina


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/

like image 25
Thy Long Avatar answered Oct 21 '22 19:10

Thy Long