// Get the drop-down custom field.
DropDownCustomField dropDownCustomField =
(DropDownCustomField) customFieldService.getCustomField(dropDownCustomFieldId);
// Get the line item.
LineItem lineItem = lineItemService.getLineItem(lineItemId);
// Create custom field values.
List<BaseCustomFieldValue> customFieldValues = new ArrayList<BaseCustomFieldValue>();
TextValue textValue = new TextValue();
textValue.setValue("Custom field value");
CustomFieldValue customFieldValue = new CustomFieldValue();
customFieldValue.setCustomFieldId(customFieldId);
customFieldValue.setValue(textValue);
customFieldValues.add(customFieldValue);
DropDownCustomFieldValue dropDownCustomFieldValue = new DropDownCustomFieldValue();
dropDownCustomFieldValue.setCustomFieldId(dropDownCustomFieldId);
dropDownCustomFieldValue.setCustomFieldOptionId(customFieldOptionId);
customFieldValues.add(dropDownCustomFieldValue);
// Only add existing custom field values for different custom fields than
// the ones you are setting.
if (lineItem.getCustomFieldValues() != null) {
for (BaseCustomFieldValue oldCustomFieldValue : lineItem.getCustomFieldValues()) {
if (!oldCustomFieldValue.getCustomFieldId().equals(customFieldId)
&& !oldCustomFieldValue.getCustomFieldId().equals(dropDownCustomFieldId)) {
customFieldValues.add(oldCustomFieldValue);
}
}
}
lineItem.setCustomFieldValues(customFieldValues.toArray(new BaseCustomFieldValue[]{}));
// Update the line item on the server.
LineItem[] lineItems = lineItemService.updateLineItems(new LineItem[] {lineItem});
if (lineItems != null) {
for (LineItem updatedLineItem : lineItems) {
List<String> customFieldValueStrings = new ArrayList<String>();
for (BaseCustomFieldValue baseCustomFieldValue : lineItem.getCustomFieldValues()) {
if (baseCustomFieldValue instanceof CustomFieldValue
&& ((CustomFieldValue) baseCustomFieldValue).getValue() instanceof TextValue) {
customFieldValueStrings.add("{ID: '" + baseCustomFieldValue.getCustomFieldId()
+ "', value: '"
+ ((TextValue) ((CustomFieldValue) baseCustomFieldValue).getValue()).getValue()
+ "'}");
} else if (baseCustomFieldValue instanceof DropDownCustomFieldValue) {
customFieldValueStrings.add("{ID: '" + baseCustomFieldValue.getCustomFieldId()
+ "', custom field option ID: '"
+ ((DropDownCustomFieldValue) baseCustomFieldValue).getCustomFieldOptionId()
+ "'}");
}
}
System.out.println("A line item with ID \"" + lineItem.getId()
+ "\" set with custom field values \""
+ StringUtils.join(customFieldValueStrings, ","));
}
} else {
System.out.println("No line items were updated.");