Saving Page Objects
EPiServer CMS 6 introduces Page Objects. A Page Object is simply a .NET object that is created by the developer and then associated to an EPiServer CMS page via the EPiServer.Core.PageData.PageObjects collection.
Saving Page Objects is a relatively simple task but there a couple of pitfalls so here are some best practice guidelines to follow:
Saving a Page Object for the first time
Create your object as normal:
1: MyClass obj = new MyClass();
2: obj.StringValue = "Hello World!";
Add the object to the PageObjects collection for the current page:
1: PageData pd = null;
2:
3: if (this.CurrentPage.IsModified)
4: {
5: pd = this.CurrentPage;
6: }
7: else
8: {
9: pd = this.CurrentPage.CreateWritableClone();
10: }
11:
12: pd.PageObjects["MyKey"] = obj;
And then save the current page (as the same version)
1: DataFactory.Instance.Save(pd,
2: EPiServer.DataAccess.SaveAction.Publish |
3: EPiServer.DataAccess.SaveAction.ForceCurrentVersion,
4: EPiServer.Security.AccessLevel.NoAccess);
Updating an existing object requires a modified flag to be set so the DataFactory knows what to update:
1: PageData pd = null;
2:
3: if (this.CurrentPage.IsModified)
4: {
5: pd = this.CurrentPage;
6: }
7: else
8: {
9: pd = this.CurrentPage.CreateWritableClone();
10: }
11:
12: // It is important to do the cloning first
13: // as the clone has a different instance of
14: // the Page Object to the original
15: // and therefore you will update the
16: // wrong version!!
17:
18: MyClass obj = pd.PageObjects["MyKey"] as MyClass;
19: obj.StringValue = this.SomeTextBox.Text;
20:
21: // Tell the collection something has changes
22: pd.PageObjects.SetObjectModified(["MyKey");
23:
24: // And Save
25: DataFactory.Instance.Save(pd,
26: EPiServer.DataAccess.SaveAction.Publish |
27: EPiServer.DataAccess.SaveAction.ForceCurrentVersion,
28: EPiServer.Security.AccessLevel.NoAccess);
IMPORTANT: Replacing an existing object will create a new row in the database if your object does not implement EPiServer.Data.Dynamic.IDynamicData as it’s identity cannot be determined.
Removing a Page Object is simple:
1: PageData pd = null;
2:
3: if (this.CurrentPage.IsModified)
4: {
5: pd = this.CurrentPage;
6: }
7: else
8: {
9: pd = this.CurrentPage.CreateWritableClone();
10: }
11:
12: pd.PageObjects.Remove("MyKey");
13:
14: DataFactory.Instance.Save(pd,
15: EPiServer.DataAccess.SaveAction.Publish |
16: EPiServer.DataAccess.SaveAction.ForceCurrentVersion,
17: EPiServer.Security.AccessLevel.NoAccess);
Comments