cancel
Showing results for 
Search instead for 
Did you mean: 

How to reset localized attribute value programmatically

Slava
Advisor
Advisor
0 Kudos

Hi experts!

Here is what I need to do. Let's say there is an item in the database with en and de locales set for a hypothetical localized attribute, e.g. attribute = [en: beer, de: bier]. I have a new locale values for the item attribute to set, e.g. [es: cerveza, pl: pivo]. If I simply call:

 modelService.setAttribute(item, 'attribute', [es: cerveza, pl: pivo]);

that will not drop previous values and as result the attribute value is [en: beer, de: bier, es: cerveza, pl: pivo] instead of just [es: cerveza, pl: pivo].

I found that making these calls

 modelService.setAttribute(item, 'attribute', null);
 modelService.setAttribute(item, 'attribute', [es: cerveza, pl: pivo]);

produces the desired result. However, I'm concerned about what if the "attribute" has optional=false in the items.xml. In this case that first call setting null has no effect and the old values are not reset. So, my question is: what's a safe and reliable way to achieve the desired result of always resetting the previous values with new ones?

Accepted Solutions (1)

Accepted Solutions (1)

Slava
Advisor
Advisor
0 Kudos

I found a solution. What I thought is working, i.e. modelService.setAttribute(item, 'attribute', null) generally did not work because this method resets only default locale value but not the whole localized values map as I was expecting. So, to make it working I had to retrieve all supported locales using the CommonI18NService, then reset value of the localized attribute to null for each supported locale. Like this:

 commonI18NService.getAllLanguages().stream()
         .map(commonI18NService::getLocaleForLanguage)                                                 
         .forEach(loc -> modelService.setAttribute(item, "attribute", loc, null))

This always reliably resets all previous locale values, before setting the new locale values. In case when the attribute is not optional in the type system, the default locale value must provided or otherwise an exception will be thrown.

Answers (0)