I am using dxa 2.2 (.net) and I created a custom Keyword Model BaseKeywordModel
that extends KeywordModel
. When DXA tries to map a published component that has a keyword field to a model that uses the BaseKeywordModel
for its keyword property it fails.
I've identified the issue. The problem occurs in the DefaultModelBuilder
class when trying to do this:
mappedValues.Add(MapKeyword((KeywordModelData) fieldValues, targetType, mappingData.Localization));
The problem here is that mappedValues
is a Generic List of BaseKeywordModel
and DXA tries to add a KeywordModel
to the list, causing an exception.
This test method causes the same issue:
[Test]
public void ModelBuilderMappedValuesTest()
{
var mappedValues = typeof(BaseKeywordModel).CreateGenericList();
var kwdModel = new KeywordModel
{
Id = "Test",
ExtensionData = new Dictionary<string, object>()
};
try
{
mappedValues.Add(kwdModel);
Assert.Equals(mappedValues.Count, 1);
}
catch
{
Assert.Fail("Error adding keyword model to list of extended keyword models");
}
}
This is the BaseKeywordModel
class:
[Include("Title", "Description", "Key")]
public class BaseKeywordModel: KeywordModel { }
I need to be able to use my own class for Keywords and was wondering whether I am doing anything wrong or this is some kind of bug in the ModelBuilder
.
It seems that by adding a Metadata Schema to the Keyword, the ModelBuilder
is capable of creating the right instance of the object, i.e. BaseKeywordModel
.
With that said, and kinda mimicking what the code does when there's a metadata schema associated to the keyword, instead of the code the ModelBuilder
uses now:
if (keywordModelData.SchemaId == null)
{
result = new KeywordModel
{
ExtensionData = keywordModelData.ExtensionData
};
}
If it would use this code:
if (keywordModelData.SchemaId == null)
{
result = (KeywordModel) targetType.CreateInstance();
result.ExtensionData = keywordModelData.ExtensionData;
}
We should be able to use our own Keyword Extended Models without the need of a metadata schema. That change shouldn't cause any regression issues as the code already does its due diligence check:
if (typeof(KeywordModel).IsAssignableFrom(targetType)) { ... }
Will try to open a support ticket to see if I can get a hotfix in place. Of course, if you guys know a different way or see I am doing something wrong, please let me know.
KeywordModel
subclass if you want to add properties which map to Keyword metadata. Can you elaborate on why you want to create a subclass for Keywords which don’t have metadata?