1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.field;
35
36
37 import info.magnolia.objectfactory.ComponentProvider;
38 import info.magnolia.ui.contentapp.FilteringMode;
39 import info.magnolia.ui.datasource.ItemResolver;
40
41 import java.util.Optional;
42
43 import javax.inject.Inject;
44
45 import com.vaadin.data.Converter;
46 import com.vaadin.data.HasValue;
47 import com.vaadin.data.Result;
48 import com.vaadin.data.ValueContext;
49
50
51
52
53
54
55
56 public class LinkFieldBinder<T> extends FieldBinder.Default<T> {
57
58 private final SelectFieldSupport<T> selectFieldSupport;
59 private final ItemResolver<T> itemResolver;
60
61 @Inject
62 LinkFieldBinder(ComponentProvider componentProvider, SelectFieldSupport<T> selectFieldSupport, ItemResolver<T> itemResolver) {
63 super(componentProvider);
64 this.selectFieldSupport = selectFieldSupport;
65 this.itemResolver = itemResolver;
66 }
67
68 @Override
69 protected <PT> Optional<Converter<PT, ?>> createConfiguredConverter(FieldDefinition<PT> definition, HasValue<?> field) {
70 Converter configuredConverter = super.createConfiguredConverter(definition, field).orElse(null);
71 if (configuredConverter == null) {
72 final Converter defaultConverter = selectFieldSupport.defaultConverter();
73 configuredConverter = field instanceof TextLinkField ? new PlainTextLinkConverter() : defaultConverter;
74 }
75 return Optional.of(configuredConverter);
76 }
77
78 private class PlainTextLinkConverter implements Converter<String, String> {
79
80 @Override
81 public Result<String> convertToModel(String value, ValueContext context) {
82 final T item = itemResolver.getItemById(value).orElse(null);
83 return item == null ? Result.ok(value) : selectFieldSupport.defaultConverter().convertToModel(item, context);
84 }
85
86 @Override
87 public String convertToPresentation(String value, ValueContext context) {
88 if (value == null) {
89 return null;
90 }
91 try {
92 final T item = selectFieldSupport.defaultConverter().convertToPresentation(value, context);
93 return item == null ? value : itemResolver.getId(item);
94 } catch (RuntimeException e) {
95 return value;
96 }
97 }
98 }
99
100
101 }