Monday, January 14, 2013

EPiServer Commerce. Loading MetaObject in meta controls explicitly.

The problem. Suppose you want to design a control for managing data in your custom meta field. You inherit CoreBaseUserControl (or BaseUserControl) class and implement IMetaControl interface. The interface contains two fields: MetaField and MetaObject. These fields are filled when you open an instance of certain meta class for edit. You use MetaField property to manage the meta field your control designed for. MetaObject is used to interact with other fields of the same item.
Sometimes you may have a dependency between fields e.g. the second control is rendered in different ways according to the value in the first field. But sometimes we get a MetaObject empty during control loading. It means that we can't access other fields without loading an object explicitly.

The solution. To address this problem we can enhance a MetaField getter in a folliwing way:

public MetaObject MetaObject
{
 get
 {
  if (this.m_metaObject == null)
  {
   const int metaObjectDefaultId = 0;
   int metaObjectId = ManagementHelper.GetIntFromQueryString("catalogentryid", metaObjectDefaultId);
   if (metaObjectId != metaObjectDefaultId && MetaField.OwnerMetaClass != null)
   {
    try
    {
     this.m_metaObject = MetaObject.Load(this.MDContext, metaObjectId, MetaField.OwnerMetaClass.Id);
    }
    catch (Exception exception)
    {
     s_logger.Error("Error retrieving MetaObject", exception);
    }
   }
  }

  return this.m_metaObject;
 }
 set
 {
  this.m_metaObject = value;
 }
}

No comments:

Post a Comment