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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Torben Junker Kjær
  • 4,042
  • 4
  • 34
  • 33

2 Answers2

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.

Nick Cipollina
  • 501
  • 3
  • 13
  • 1
    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. – Torben Junker Kjær Feb 16 '15 at 10:24
  • 2
    @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 :) – David Masters Feb 05 '16 at 10:28
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/

Thy Long
  • 11
  • 2