cancel
Showing results for 
Search instead for 
Did you mean: 

model service create() vs model service initdefault()?

krishn_signet
Participant
0 Kudos

ModelService's create method internally calls initDefault() method then why do we have these two public methods? We can simple call create() and it can internally call the other one.

Accepted Solutions (0)

Answers (1)

Answers (1)

former_member620692
Active Contributor
0 Kudos

I agree with you. If the purpose of initDefault() was just to keep the code modular and clean, it could have been kept private instead of public.

Executing the following code in groovy console:

 testProduct = modelService.create('Product')
 println ('Code: '+testProduct.code+', Price Quantity: '+testProduct.priceQuantity+', Catalog Version: '+testProduct.catalogVersion)
 
 testProduct.code = "12345"
 testProduct.priceQuantity=2.0
 testProduct.catalogVersion = catalogVersionService.getCatalogVersion('Default', 'Staged')
 println ('Code: '+testProduct.code+', Price Quantity: '+testProduct.priceQuantity+', Catalog Version: '+testProduct.catalogVersion)
 
 modelService.initDefaults(testProduct)
 println ('Code: '+testProduct.code+', Price Quantity: '+testProduct.priceQuantity+', Catalog Version: '+testProduct.catalogVersion)
 
 try {
     p = flexibleSearchService.getModelByExample testProduct
 } catch (e) {
     p = testProduct
 }
 println ('Code: '+p.code+', Price Quantity: '+p.priceQuantity+', Catalog Version: '+p.catalogVersion)
 
 modelService.initDefaults(p)
 println ('Code: '+p.code+', Price Quantity: '+p.priceQuantity+', Catalog Version: '+p.catalogVersion)

results in the following output:

 Code: null, Price Quantity: 1.0, Catalog Version: null
 Code: 12345, Price Quantity: 2.0, Catalog Version: CatalogVersionModel (8796093088345@4)
 Code: 12345, Price Quantity: 2.0, Catalog Version: CatalogVersionModel (8796093088345@4)
 Code: 12345, Price Quantity: 2.0, Catalog Version: CatalogVersionModel (8796093088345@4)
 Code: 12345, Price Quantity: 2.0, Catalog Version: CatalogVersionModel (8796093088345@4)

which means that if the model attributes are already assigned some value, they will not be reset to null or default values by calling modelService.initDefaults(model).

krishn_signet
Participant
0 Kudos

Ok but I don't think you have given default values for those attributes in items.xml right? When we use init default will assign default values for perticular attribute which have default value defined in items.xml.

Correct me if I am wrong.

former_member620692
Active Contributor
0 Kudos

modelService.initDefaults(model) sets the default value of attributes as set in items.xml e.g. the default value of priceQuantity has been set as 1.0 in items.xml and therefore as you can see in the output above, it has been printed as 1.0. If modelService.initDefaults(model) does not find a default value in items.xml, it assigns the default value as per Java rule (e.g. null to an object).