This post is part of a series. In the previous article I explained how you can create your own ViewModels in a few minutes.
In this post we will look at number and date fields. We will also learn how to model multiple value fields and metadata fields.
First, we will add a few fields to our schema, like this:
Fields | |
publishDate | Date/time, single value |
lottoNumbers | Number, multiple value |
Now let’s model the first field, publishDate. This is a date/time field in SDL. We will model it – as you would expect – as a DateTime field, like this:
[DateField]
public DateTime PublishDate { get; set; }
Now on to the next field. We could model it like this:
[NumberField]
public double LottoNumbers { get; set; }
Although this works, it is probably not what you want. This will return the first value only of this multiple value field.
To access all the values, simply change the property type to a List, like this:
[NumberField]
public List<double> LottoNumbers { get; set; }
Simple enough, right?
Metadata
Up until now, all the fields we have modeled were coming from the content of a component. But what about metadata? Can we model metadata fields as well?
Of course! It is – again – very simple:
[NumberField (IsMetadata = true)]
public List<double> LottoNumbers { get; set; }
Of course, this only works if ‘lottoNumbers’ is a metadata field. If it would be a content field, the value of the property would always be null.
Now that we’re on the topic of ‘missing properties’, it is good to know that a view model can be created even if some of the fields are missing from the content item. That’s just as well, because in some cases (if a field is optional), not all components may contain all the fields defined in a schema.
At this moment, there is no way in the DD4T View Models to enforce a field to be mandatory. If a field is missing from the component, the value of the property will be the default value for its type. For complex types like String, the default is null, for simple types like double or DateTime, it will be whatever the ‘default’ keyword returns (see https://msdn.microsoft.com/nl-nl/library/83fhsxwc.aspx).
Perhaps – if there is enough demand – the DD4T community will make it possible to mark properties as mandatory. In that case the creation of a ViewModel fails if the field is missing. If you are interested in that functionality, you are free to create a ticket for it.