Can I set a default value for a field in a type?

#1

I want to set a default value for certain fields in a type, however I also have seed data for this type that I would like to take precedence over this default value.

For example:
c3Type file:
entity type TestType {
varA: int = 5
}

seed file 1:
{
“id”: “ExampleTestType_1”,
“varA”: 10
}

seed file 2:
{
“id”: “ExampleTestType_2”,
}

Now when I provision and do a fetch on this type, I will still see the default value to be 5, even though I had seed data that changed varA for one of the entries to 10. Is this expected behavior?

0 Likes

Setting constant values in a type
#2

Try this:

entity type TestType {
  varA: int post default '5'
}
0 Likes

#3

In other words,
varA: int = 5
will make the value of varA ALWAYS 5, while
varA: int post default '5'
will make the value of varA 5 only when the varA field is not supplied during object creation?

0 Likes

#4

Thanks for the replies. Upon further investigation, when I do varA: int = 5, it works actually and if seed data is present, that will take precedence. However, I tried the method that Matt mentioned and I do not see the default value being set. so if I were to do varA: int post default ‘5’, I do not see the value being set if nothing is provided. Could this be a bug?

0 Likes

#5

You should not use int = 5. That is an obj initializer which means that an obj instance will have the value 5 upon instantiation. While this will “work” for new data created, the downside is that if you add/change the default value and there are existing instances in the db with null values, then they will appear to have the value 5 when you fetch them but they will really be null and you won’t find them with searching.

The int post default ‘5’ is intended to do what you are asking. If it is not, please file a ticket with repro steps and I’ll investigate

2 Likes

Field initializers
Defaulting mandatory fields from a canonical type
#6

Thanks I will verify and open ticket if it does not work as you described.

0 Likes