summaryrefslogtreecommitdiffstats
path: root/server/src/com/vaadin/ui/Form.java
blob: a1ec0f991726755bb0bdb94f823155b8dad43c80 (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
/* 
 * Copyright 2011 Vaadin Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.vaadin.ui;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import com.vaadin.data.Buffered;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Validatable;
import com.vaadin.data.Validator;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.util.BeanItem;
import com.vaadin.event.Action;
import com.vaadin.event.Action.Handler;
import com.vaadin.event.Action.ShortcutNotifier;
import com.vaadin.event.ActionManager;
import com.vaadin.shared.ui.form.FormState;
import com.vaadin.terminal.AbstractErrorMessage;
import com.vaadin.terminal.CompositeErrorMessage;
import com.vaadin.terminal.ErrorMessage;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.terminal.UserError;
import com.vaadin.terminal.Vaadin6Component;

/**
 * Form component provides easy way of creating and managing sets fields.
 * 
 * <p>
 * <code>Form</code> is a container for fields implementing {@link Field}
 * interface. It provides support for any layouts and provides buffering
 * interface for easy connection of commit and discard buttons. All the form
 * fields can be customized by adding validators, setting captions and icons,
 * setting immediateness, etc. Also direct mechanism for replacing existing
 * fields with selections is given.
 * </p>
 * 
 * <p>
 * <code>Form</code> provides customizable editor for classes implementing
 * {@link com.vaadin.data.Item} interface. Also the form itself implements this
 * interface for easier connectivity to other items. To use the form as editor
 * for an item, just connect the item to form with
 * {@link Form#setItemDataSource(Item)}. If only a part of the item needs to be
 * edited, {@link Form#setItemDataSource(Item,Collection)} can be used instead.
 * After the item has been connected to the form, the automatically created
 * fields can be customized and new fields can be added. If you need to connect
 * a class that does not implement {@link com.vaadin.data.Item} interface, most
 * properties of any class following bean pattern, can be accessed trough
 * {@link com.vaadin.data.util.BeanItem}.
 * </p>
 * 
 * @author Vaadin Ltd.
 * @since 3.0
 * @deprecated Use {@link FieldGroup} instead of {@link Form} for more
 *             flexibility.
 */
@Deprecated
public class Form extends AbstractField<Object> implements Item.Editor,
        Buffered, Item, Validatable, Action.Notifier, HasComponents,
        Vaadin6Component {

    private Object propertyValue;

    /**
     * Item connected to this form as datasource.
     */
    private Item itemDatasource;

    /**
     * Ordered list of property ids in this editor.
     */
    private final LinkedList<Object> propertyIds = new LinkedList<Object>();

    /**
     * Current buffered source exception.
     */
    private Buffered.SourceException currentBufferedSourceException = null;

    /**
     * Is the form in write trough mode.
     */
    private boolean writeThrough = true;

    /**
     * Is the form in read trough mode.
     */
    private boolean readThrough = true;

    /**
     * Mapping from propertyName to corresponding field.
     */
    private final HashMap<Object, Field<?>> fields = new HashMap<Object, Field<?>>();

    /**
     * Form may act as an Item, its own properties are stored here.
     */
    private final HashMap<Object, Property<?>> ownProperties = new HashMap<Object, Property<?>>();

    /**
     * Field factory for this form.
     */
    private FormFieldFactory fieldFactory;

    /**
     * Visible item properties.
     */
    private Collection<?> visibleItemProperties;

    /**
     * Form needs to repaint itself if child fields value changes due possible
     * change in form validity.
     * 
     * TODO introduce ValidityChangeEvent (#6239) and start using it instead.
     * See e.g. DateField#notifyFormOfValidityChange().
     */
    private final ValueChangeListener fieldValueChangeListener = new ValueChangeListener() {
        @Override
        public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
            requestRepaint();
        }
    };

    /**
     * If this is true, commit implicitly calls setValidationVisible(true).
     */
    private boolean validationVisibleOnCommit = true;

    // special handling for gridlayout; remember initial cursor pos
    private int gridlayoutCursorX = -1;
    private int gridlayoutCursorY = -1;

    /**
     * Keeps track of the Actions added to this component, and manages the
     * painting and handling as well. Note that the extended AbstractField is a
     * {@link ShortcutNotifier} and has a actionManager that delegates actions
     * to the containing window. This one does not delegate.
     */
    private ActionManager ownActionManager = new ActionManager(this);

    /**
     * Constructs a new form with default layout.
     * 
     * <p>
     * By default the form uses {@link FormLayout}.
     * </p>
     */
    public Form() {
        this(null);
        setValidationVisible(false);
    }

    /**
     * Constructs a new form with given {@link Layout}.
     * 
     * @param formLayout
     *            the layout of the form.
     */
    public Form(Layout formLayout) {
        this(formLayout, DefaultFieldFactory.get());
    }

    /**
     * Constructs a new form with given {@link Layout} and
     * {@link FormFieldFactory}.
     * 
     * @param formLayout
     *            the layout of the form.
     * @param fieldFactory
     *            the FieldFactory of the form.
     */
    public Form(Layout formLayout, FormFieldFactory fieldFactory) {
        super();
        setLayout(formLayout);
        setFooter(null);
        setFormFieldFactory(fieldFactory);
        setValidationVisible(false);
        setWidth(100, UNITS_PERCENTAGE);
    }

    @Override
    public FormState getState() {
        return (FormState) super.getState();
    }

    /* Documented in interface */
    @Override
    public void paintContent(PaintTarget target) throws PaintException {
        if (ownActionManager != null) {
            ownActionManager.paintActions(null, target);
        }
    }

    @Override
    public void changeVariables(Object source, Map<String, Object> variables) {
        // Actions
        if (ownActionManager != null) {
            ownActionManager.handleActions(variables, this);
        }
    }

    /**
     * The error message of a Form is the error of the first field with a
     * non-empty error.
     * 
     * Empty error messages of the contained fields are skipped, because an
     * empty error indicator would be confusing to the user, especially if there
     * are errors that have something to display. This is also the reason why
     * the calculation of the error message is separate from validation, because
     * validation fails also on empty errors.
     */
    @Override
    public ErrorMessage getErrorMessage() {

        // Reimplement the checking of validation error by using
        // getErrorMessage() recursively instead of validate().
        ErrorMessage validationError = null;
        if (isValidationVisible()) {
            for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
                Object f = fields.get(i.next());
                if (f instanceof AbstractComponent) {
                    AbstractComponent field = (AbstractComponent) f;

                    validationError = field.getErrorMessage();
                    if (validationError != null) {
                        // Show caption as error for fields with empty errors
                        if ("".equals(validationError.toString())) {
                            validationError = new UserError(field.getCaption());
                        }
                        break;
                    } else if (f instanceof Field && !((Field<?>) f).isValid()) {
                        // Something is wrong with the field, but no proper
                        // error is given. Generate one.
                        validationError = new UserError(field.getCaption());
                        break;
                    }
                }
            }
        }

        // Return if there are no errors at all
        if (getComponentError() == null && validationError == null
                && currentBufferedSourceException == null) {
            return null;
        }

        // Throw combination of the error types
        return new CompositeErrorMessage(
                new ErrorMessage[] {
                        getComponentError(),
                        validationError,
                        AbstractErrorMessage
                                .getErrorMessageForException(currentBufferedSourceException) });
    }

    /**
     * Controls the making validation visible implicitly on commit.
     * 
     * Having commit() call setValidationVisible(true) implicitly is the default
     * behaviour. You can disable the implicit setting by setting this property
     * as false.
     * 
     * It is useful, because you usually want to start with the form free of
     * errors and only display them after the user clicks Ok. You can disable
     * the implicit setting by setting this property as false.
     * 
     * @param makeVisible
     *            If true (default), validation is made visible when commit() is
     *            called. If false, the visibility is left as it is.
     */
    public void setValidationVisibleOnCommit(boolean makeVisible) {
        validationVisibleOnCommit = makeVisible;
    }

    /**
     * Is validation made automatically visible on commit?
     * 
     * See setValidationVisibleOnCommit().
     * 
     * @return true if validation is made automatically visible on commit.
     */
    public boolean isValidationVisibleOnCommit() {
        return validationVisibleOnCommit;
    }

    /*
     * Commit changes to the data source Don't add a JavaDoc comment here, we
     * use the default one from the interface.
     */
    @Override
    public void commit() throws Buffered.SourceException, InvalidValueException {

        LinkedList<SourceException> problems = null;

        // Only commit on valid state if so requested
        if (!isInvalidCommitted() && !isValid()) {
            /*
             * The values are not ok and we are told not to commit invalid
             * values
             */
            if (validationVisibleOnCommit) {
                setValidationVisible(true);
            }

            // Find the first invalid value and throw the exception
            validate();
        }

        // Try to commit all
        for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
            try {
                final Field<?> f = (fields.get(i.next()));
                // Commit only non-readonly fields.
                if (!f.isReadOnly()) {
                    f.commit();
                }
            } catch (final Buffered.SourceException e) {
                if (problems == null) {
                    problems = new LinkedList<SourceException>();
                }
                problems.add(e);
            }
        }

        // No problems occurred
        if (problems == null) {
            if (currentBufferedSourceException != null) {
                currentBufferedSourceException = null;
                requestRepaint();
            }
            return;
        }

        // Commit problems
        final Throwable[] causes = new Throwable[problems.size()];
        int index = 0;
        for (final Iterator<SourceException> i = problems.iterator(); i
                .hasNext();) {
            causes[index++] = i.next();
        }
        final Buffered.SourceException e = new Buffered.SourceException(this,
                causes);
        currentBufferedSourceException = e;
        requestRepaint();
        throw e;
    }

    /*
     * Discards local changes and refresh values from the data source Don't add
     * a JavaDoc comment here, we use the default one from the interface.
     */
    @Override
    public void discard() throws Buffered.SourceException {

        LinkedList<SourceException> problems = null;

        // Try to discard all changes
        for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
            try {
                (fields.get(i.next())).discard();
            } catch (final Buffered.SourceException e) {
                if (problems == null) {
                    problems = new LinkedList<SourceException>();
                }
                problems.add(e);
            }
        }

        // No problems occurred
        if (problems == null) {
            if (currentBufferedSourceException != null) {
                currentBufferedSourceException = null;
                requestRepaint();
            }
            return;
        }

        // Discards problems occurred
        final Throwable[] causes = new Throwable[problems.size()];
        int index = 0;
        for (final Iterator<SourceException> i = problems.iterator(); i
                .hasNext();) {
            causes[index++] = i.next();
        }
        final Buffered.SourceException e = new Buffered.SourceException(this,
                causes);
        currentBufferedSourceException = e;
        requestRepaint();
        throw e;
    }

    /*
     * Is the object modified but not committed? Don't add a JavaDoc comment
     * here, we use the default one from the interface.
     */
    @Override
    public boolean isModified() {
        for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
            final Field<?> f = fields.get(i.next());
            if (f != null && f.isModified()) {
                return true;
            }

        }
        return false;
    }

    /*
     * Is the editor in a read-through mode? Don't add a JavaDoc comment here,
     * we use the default one from the interface.
     */
    @Override
    @Deprecated
    public boolean isReadThrough() {
        return readThrough;
    }

    /*
     * Is the editor in a write-through mode? Don't add a JavaDoc comment here,
     * we use the default one from the interface.
     */
    @Override
    @Deprecated
    public boolean isWriteThrough() {
        return writeThrough;
    }

    /*
     * Sets the editor's read-through mode to the specified status. Don't add a
     * JavaDoc comment here, we use the default one from the interface.
     */
    @Override
    public void setReadThrough(boolean readThrough) {
        if (readThrough != this.readThrough) {
            this.readThrough = readThrough;
            for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
                (fields.get(i.next())).setReadThrough(readThrough);
            }
        }
    }

    /*
     * Sets the editor's read-through mode to the specified status. Don't add a
     * JavaDoc comment here, we use the default one from the interface.
     */
    @Override
    public void setWriteThrough(boolean writeThrough) throws SourceException,
            InvalidValueException {
        if (writeThrough != this.writeThrough) {
            this.writeThrough = writeThrough;
            for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
                (fields.get(i.next())).setWriteThrough(writeThrough);
            }
        }
    }

    /**
     * Adds a new property to form and create corresponding field.
     * 
     * @see com.vaadin.data.Item#addItemProperty(Object, Property)
     */
    @Override
    public boolean addItemProperty(Object id, Property property) {

        // Checks inputs
        if (id == null || property == null) {
            throw new NullPointerException("Id and property must be non-null");
        }

        // Checks that the property id is not reserved
        if (propertyIds.contains(id)) {
            return false;
        }

        propertyIds.add(id);
        ownProperties.put(id, property);

        // Gets suitable field
        final Field<?> field = fieldFactory.createField(this, id, this);
        if (field == null) {
            return false;
        }

        // Configures the field
        bindPropertyToField(id, property, field);

        // Register and attach the created field
        addField(id, field);

        return true;
    }

    /**
     * Registers the field with the form and adds the field to the form layout.
     * 
     * <p>
     * The property id must not be already used in the form.
     * </p>
     * 
     * <p>
     * This field is added to the layout using the
     * {@link #attachField(Object, Field)} method.
     * </p>
     * 
     * @param propertyId
     *            the Property id the the field.
     * @param field
     *            the field which should be added to the form.
     */
    public void addField(Object propertyId, Field<?> field) {
        registerField(propertyId, field);
        attachField(propertyId, field);
        requestRepaint();
    }

    /**
     * Register the field with the form. All registered fields are validated
     * when the form is validated and also committed when the form is committed.
     * 
     * <p>
     * The property id must not be already used in the form.
     * </p>
     * 
     * 
     * @param propertyId
     *            the Property id of the field.
     * @param field
     *            the Field that should be registered
     */
    private void registerField(Object propertyId, Field<?> field) {
        if (propertyId == null || field == null) {
            return;
        }

        fields.put(propertyId, field);
        field.addListener(fieldValueChangeListener);
        if (!propertyIds.contains(propertyId)) {
            // adding a field directly
            propertyIds.addLast(propertyId);
        }

        // Update the read and write through status and immediate to match the
        // form.
        // Should this also include invalidCommitted (#3993)?
        field.setReadThrough(readThrough);
        field.setWriteThrough(writeThrough);
        if (isImmediate() && field instanceof AbstractComponent) {
            ((AbstractComponent) field).setImmediate(true);
        }
    }

    /**
     * Adds the field to the form layout.
     * <p>
     * The field is added to the form layout in the default position (the
     * position used by {@link Layout#addComponent(Component)}. If the
     * underlying layout is a {@link CustomLayout} the field is added to the
     * CustomLayout location given by the string representation of the property
     * id using {@link CustomLayout#addComponent(Component, String)}.
     * </p>
     * 
     * <p>
     * Override this method to control how the fields are added to the layout.
     * </p>
     * 
     * @param propertyId
     * @param field
     */
    protected void attachField(Object propertyId, Field field) {
        if (propertyId == null || field == null) {
            return;
        }

        Layout layout = getLayout();
        if (layout instanceof CustomLayout) {
            ((CustomLayout) layout).addComponent(field, propertyId.toString());
        } else {
            layout.addComponent(field);
        }

    }

    /**
     * The property identified by the property id.
     * 
     * <p>
     * The property data source of the field specified with property id is
     * returned. If there is a (with specified property id) having no data
     * source, the field is returned instead of the data source.
     * </p>
     * 
     * @see com.vaadin.data.Item#getItemProperty(Object)
     */
    @Override
    public Property<?> getItemProperty(Object id) {
        final Field<?> field = fields.get(id);
        if (field == null) {
            // field does not exist or it is not (yet) created for this property
            return ownProperties.get(id);
        }
        final Property<?> property = field.getPropertyDataSource();

        if (property != null) {
            return property;
        } else {
            return field;
        }
    }

    /**
     * Gets the field identified by the propertyid.
     * 
     * @param propertyId
     *            the id of the property.
     */
    public Field<?> getField(Object propertyId) {
        return fields.get(propertyId);
    }

    /* Documented in interface */
    @Override
    public Collection<?> getItemPropertyIds() {
        return Collections.unmodifiableCollection(propertyIds);
    }

    /**
     * Removes the property and corresponding field from the form.
     * 
     * @see com.vaadin.data.Item#removeItemProperty(Object)
     */
    @Override
    public boolean removeItemProperty(Object id) {
        ownProperties.remove(id);

        final Field<?> field = fields.get(id);

        if (field != null) {
            propertyIds.remove(id);
            fields.remove(id);
            detachField(field);
            field.removeListener(fieldValueChangeListener);
            return true;
        }

        return false;
    }

    /**
     * Called when a form field is detached from a Form. Typically when a new
     * Item is assigned to Form via {@link #setItemDataSource(Item)}.
     * <p>
     * Override this method to control how the fields are removed from the
     * layout.
     * </p>
     * 
     * @param field
     *            the field to be detached from the forms layout.
     */
    protected void detachField(final Field field) {
        Component p = field.getParent();
        if (p instanceof ComponentContainer) {
            ((ComponentContainer) p).removeComponent(field);
        }
    }

    /**
     * Removes all properties and fields from the form.
     * 
     * @return the Success of the operation. Removal of all fields succeeded if
     *         (and only if) the return value is <code>true</code>.
     */
    public boolean removeAllProperties() {
        final Object[] properties = propertyIds.toArray();
        boolean success = true;

        for (int i = 0; i < properties.length; i++) {
            if (!removeItemProperty(properties[i])) {
                success = false;
            }
        }

        return success;
    }

    /* Documented in the interface */
    @Override
    public Item getItemDataSource() {
        return itemDatasource;
    }

    /**
     * Sets the item datasource for the form.
     * 
     * <p>
     * Setting item datasource clears any fields, the form might contain and
     * adds all the properties as fields to the form.
     * </p>
     * 
     * @see com.vaadin.data.Item.Viewer#setItemDataSource(Item)
     */
    @Override
    public void setItemDataSource(Item newDataSource) {
        setItemDataSource(newDataSource,
                newDataSource != null ? newDataSource.getItemPropertyIds()
                        : null);
    }

    /**
     * Set the item datasource for the form, but limit the form contents to
     * specified properties of the item.
     * 
     * <p>
     * Setting item datasource clears any fields, the form might contain and
     * adds the specified the properties as fields to the form, in the specified
     * order.
     * </p>
     * 
     * @see com.vaadin.data.Item.Viewer#setItemDataSource(Item)
     */
    public void setItemDataSource(Item newDataSource, Collection<?> propertyIds) {

        if (getLayout() instanceof GridLayout) {
            GridLayout gl = (GridLayout) getLayout();
            if (gridlayoutCursorX == -1) {
                // first setItemDataSource, remember initial cursor
                gridlayoutCursorX = gl.getCursorX();
                gridlayoutCursorY = gl.getCursorY();
            } else {
                // restore initial cursor
                gl.setCursorX(gridlayoutCursorX);
                gl.setCursorY(gridlayoutCursorY);
            }
        }

        // Removes all fields first from the form
        removeAllProperties();

        // Sets the datasource
        itemDatasource = newDataSource;

        // If the new datasource is null, just set null datasource
        if (itemDatasource == null) {
            requestRepaint();
            return;
        }

        // Adds all the properties to this form
        for (final Iterator<?> i = propertyIds.iterator(); i.hasNext();) {
            final Object id = i.next();
            final Property<?> property = itemDatasource.getItemProperty(id);
            if (id != null && property != null) {
                final Field<?> f = fieldFactory.createField(itemDatasource, id,
                        this);
                if (f != null) {
                    bindPropertyToField(id, property, f);
                    addField(id, f);
                }
            }
        }
    }

    /**
     * Binds an item property to a field. The default behavior is to bind
     * property straight to Field. If Property.Viewer type property (e.g.
     * PropertyFormatter) is already set for field, the property is bound to
     * that Property.Viewer.
     * 
     * @param propertyId
     * @param property
     * @param field
     * @since 6.7.3
     */
    protected void bindPropertyToField(final Object propertyId,
            final Property property, final Field field) {
        // check if field has a property that is Viewer set. In that case we
        // expect developer has e.g. PropertyFormatter that he wishes to use and
        // assign the property to the Viewer instead.
        boolean hasFilterProperty = field.getPropertyDataSource() != null
                && (field.getPropertyDataSource() instanceof Property.Viewer);
        if (hasFilterProperty) {
            ((Property.Viewer) field.getPropertyDataSource())
                    .setPropertyDataSource(property);
        } else {
            field.setPropertyDataSource(property);
        }
    }

    /**
     * Gets the layout of the form.
     * 
     * <p>
     * By default form uses <code>OrderedLayout</code> with <code>form</code>
     * -style.
     * </p>
     * 
     * @return the Layout of the form.
     */
    public Layout getLayout() {
        return (Layout) getState().getLayout();
    }

    /**
     * Sets the layout of the form.
     * 
     * <p>
     * If set to null then Form uses a FormLayout by default.
     * </p>
     * 
     * @param layout
     *            the layout of the form.
     */
    public void setLayout(Layout layout) {

        // Use orderedlayout by default
        if (layout == null) {
            layout = new FormLayout();
        }

        // reset cursor memory
        gridlayoutCursorX = -1;
        gridlayoutCursorY = -1;

        // Move fields from previous layout
        if (getLayout() != null) {
            final Object[] properties = propertyIds.toArray();
            for (int i = 0; i < properties.length; i++) {
                Field<?> f = getField(properties[i]);
                detachField(f);
                if (layout instanceof CustomLayout) {
                    ((CustomLayout) layout).addComponent(f,
                            properties[i].toString());
                } else {
                    layout.addComponent(f);
                }
            }

            getLayout().setParent(null);
        }

        // Replace the previous layout
        layout.setParent(this);
        getState().setLayout(layout);

        // Hierarchy has changed so we need to repaint (this could be a
        // hierarchy repaint only)
        requestRepaint();
    }

    /**
     * Sets the form field to be selectable from static list of changes.
     * 
     * <p>
     * The list values and descriptions are given as array. The value-array must
     * contain the current value of the field and the lengths of the arrays must
     * match. Null values are not supported.
     * </p>
     * 
     * Note: since Vaadin 7.0, returns an {@link AbstractSelect} instead of a
     * {@link Select}.
     * 
     * @param propertyId
     *            the id of the property.
     * @param values
     * @param descriptions
     * @return the select property generated
     */
    public AbstractSelect replaceWithSelect(Object propertyId, Object[] values,
            Object[] descriptions) {

        // Checks the parameters
        if (propertyId == null || values == null || descriptions == null) {
            throw new NullPointerException("All parameters must be non-null");
        }
        if (values.length != descriptions.length) {
            throw new IllegalArgumentException(
                    "Value and description list are of different size");
        }

        // Gets the old field
        final Field<?> oldField = fields.get(propertyId);
        if (oldField == null) {
            throw new IllegalArgumentException("Field with given propertyid '"
                    + propertyId.toString() + "' can not be found.");
        }
        final Object value = oldField.getPropertyDataSource() == null ? oldField
                .getValue() : oldField.getPropertyDataSource().getValue();

        // Checks that the value exists and check if the select should
        // be forced in multiselect mode
        boolean found = false;
        boolean isMultiselect = false;
        for (int i = 0; i < values.length && !found; i++) {
            if (values[i] == value
                    || (value != null && value.equals(values[i]))) {
                found = true;
            }
        }
        if (value != null && !found) {
            if (value instanceof Collection) {
                for (final Iterator<?> it = ((Collection<?>) value).iterator(); it
                        .hasNext();) {
                    final Object val = it.next();
                    found = false;
                    for (int i = 0; i < values.length && !found; i++) {
                        if (values[i] == val
                                || (val != null && val.equals(values[i]))) {
                            found = true;
                        }
                    }
                    if (!found) {
                        throw new IllegalArgumentException(
                                "Currently selected value '" + val
                                        + "' of property '"
                                        + propertyId.toString()
                                        + "' was not found");
                    }
                }
                isMultiselect = true;
            } else {
                throw new IllegalArgumentException("Current value '" + value
                        + "' of property '" + propertyId.toString()
                        + "' was not found");
            }
        }

        // Creates the new field matching to old field parameters
        final AbstractSelect newField = isMultiselect ? new ListSelect()
                : new Select();
        newField.setCaption(oldField.getCaption());
        newField.setReadOnly(oldField.isReadOnly());
        newField.setReadThrough(oldField.isReadThrough());
        newField.setWriteThrough(oldField.isWriteThrough());

        // Creates the options list
        newField.addContainerProperty("desc", String.class, "");
        newField.setItemCaptionPropertyId("desc");
        for (int i = 0; i < values.length; i++) {
            Object id = values[i];
            final Item item;
            if (id == null) {
                id = newField.addItem();
                item = newField.getItem(id);
                newField.setNullSelectionItemId(id);
            } else {
                item = newField.addItem(id);
            }

            if (item != null) {
                item.getItemProperty("desc").setValue(
                        descriptions[i].toString());
            }
        }

        // Sets the property data source
        final Property<?> property = oldField.getPropertyDataSource();
        oldField.setPropertyDataSource(null);
        newField.setPropertyDataSource(property);

        // Replaces the old field with new one
        getLayout().replaceComponent(oldField, newField);
        fields.put(propertyId, newField);
        newField.addListener(fieldValueChangeListener);
        oldField.removeListener(fieldValueChangeListener);

        return newField;
    }

    /**
     * Checks the validity of the Form and all of its fields.
     * 
     * @see com.vaadin.data.Validatable#validate()
     */
    @Override
    public void validate() throws InvalidValueException {
        super.validate();
        for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
            (fields.get(i.next())).validate();
        }
    }

    /**
     * Checks the validabtable object accept invalid values.
     * 
     * @see com.vaadin.data.Validatable#isInvalidAllowed()
     */
    @Override
    public boolean isInvalidAllowed() {
        return true;
    }

    /**
     * Should the validabtable object accept invalid values.
     * 
     * @see com.vaadin.data.Validatable#setInvalidAllowed(boolean)
     */
    @Override
    public void setInvalidAllowed(boolean invalidValueAllowed)
            throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
     * Sets the component's to read-only mode to the specified state.
     * 
     * @see com.vaadin.ui.Component#setReadOnly(boolean)
     */
    @Override
    public void setReadOnly(boolean readOnly) {
        super.setReadOnly(readOnly);
        for (final Iterator<?> i = propertyIds.iterator(); i.hasNext();) {
            (fields.get(i.next())).setReadOnly(readOnly);
        }
    }

    /**
     * Sets the field factory used by this Form to genarate Fields for
     * properties.
     * 
     * {@link FormFieldFactory} is used to create fields for form properties.
     * {@link DefaultFieldFactory} is used by default.
     * 
     * @param fieldFactory
     *            the new factory used to create the fields.
     * @see Field
     * @see FormFieldFactory
     */
    public void setFormFieldFactory(FormFieldFactory fieldFactory) {
        this.fieldFactory = fieldFactory;
    }

    /**
     * Get the field factory of the form.
     * 
     * @return the FormFieldFactory Factory used to create the fields.
     */
    public FormFieldFactory getFormFieldFactory() {
        return fieldFactory;
    }

    /**
     * Gets the field type.
     * 
     * @see com.vaadin.ui.AbstractField#getType()
     */
    @Override
    public Class<?> getType() {
        if (getPropertyDataSource() != null) {
            return getPropertyDataSource().getType();
        }
        return Object.class;
    }

    /**
     * Sets the internal value.
     * 
     * This is relevant when the Form is used as Field.
     * 
     * @see com.vaadin.ui.AbstractField#setInternalValue(java.lang.Object)
     */
    @Override
    protected void setInternalValue(Object newValue) {
        // Stores the old value
        final Object oldValue = propertyValue;

        // Sets the current Value
        super.setInternalValue(newValue);
        propertyValue = newValue;

        // Ignores form updating if data object has not changed.
        if (oldValue != newValue) {
            setFormDataSource(newValue, getVisibleItemProperties());
        }
    }

    /**
     * Gets the first focusable field in form. If there are enabled,
     * non-read-only fields, the first one of them is returned. Otherwise, the
     * field for the first property (or null if none) is returned.
     * 
     * @return the Field.
     */
    private Field<?> getFirstFocusableField() {
        if (getItemPropertyIds() != null) {
            for (Object id : getItemPropertyIds()) {
                if (id != null) {
                    Field<?> field = getField(id);
                    if (field.isEnabled() && !field.isReadOnly()) {
                        return field;
                    }
                }
            }
            // fallback: first field if none of the fields is enabled and
            // writable
            Object id = getItemPropertyIds().iterator().next();
            if (id != null) {
                return getField(id);
            }
        }
        return null;
    }

    /**
     * Updates the internal form datasource.
     * 
     * Method setFormDataSource.
     * 
     * @param data
     * @param properties
     */
    protected void setFormDataSource(Object data, Collection<?> properties) {

        // If data is an item use it.
        Item item = null;
        if (data instanceof Item) {
            item = (Item) data;
        } else if (data != null) {
            item = new BeanItem<Object>(data);
        }

        // Sets the datasource to form
        if (item != null && properties != null) {
            // Shows only given properties
            this.setItemDataSource(item, properties);
        } else {
            // Shows all properties
            this.setItemDataSource(item);
        }
    }

    /**
     * Returns the visibleProperties.
     * 
     * @return the Collection of visible Item properites.
     */
    public Collection<?> getVisibleItemProperties() {
        return visibleItemProperties;
    }

    /**
     * Sets the visibleProperties.
     * 
     * @param visibleProperties
     *            the visibleProperties to set.
     */
    public void setVisibleItemProperties(Collection<?> visibleProperties) {
        visibleItemProperties = visibleProperties;
        Object value = getValue();
        if (value == null) {
            value = itemDatasource;
        }
        setFormDataSource(value, getVisibleItemProperties());
    }

    /**
     * Sets the visibleProperties.
     * 
     * @param visibleProperties
     *            the visibleProperties to set.
     */
    public void setVisibleItemProperties(Object[] visibleProperties) {
        LinkedList<Object> v = new LinkedList<Object>();
        for (int i = 0; i < visibleProperties.length; i++) {
            v.add(visibleProperties[i]);
        }
        setVisibleItemProperties(v);
    }

    /**
     * Focuses the first field in the form.
     * 
     * @see com.vaadin.ui.Component.Focusable#focus()
     */
    @Override
    public void focus() {
        final Field<?> f = getFirstFocusableField();
        if (f != null) {
            f.focus();
        }
    }

    /**
     * Sets the Tabulator index of this Focusable component.
     * 
     * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
     */
    @Override
    public void setTabIndex(int tabIndex) {
        super.setTabIndex(tabIndex);
        for (final Iterator<?> i = getItemPropertyIds().iterator(); i.hasNext();) {
            (getField(i.next())).setTabIndex(tabIndex);
        }
    }

    /**
     * Setting the form to be immediate also sets all the fields of the form to
     * the same state.
     */
    @Override
    public void setImmediate(boolean immediate) {
        super.setImmediate(immediate);
        for (Iterator<Field<?>> i = fields.values().iterator(); i.hasNext();) {
            Field<?> f = i.next();
            if (f instanceof AbstractComponent) {
                ((AbstractComponent) f).setImmediate(immediate);
            }
        }
    }

    /** Form is empty if all of its fields are empty. */
    @Override
    protected boolean isEmpty() {

        for (Iterator<Field<?>> i = fields.values().iterator(); i.hasNext();) {
            Field<?> f = i.next();
            if (f instanceof AbstractField) {
                if (!((AbstractField<?>) f).isEmpty()) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Adding validators directly to form is not supported.
     * 
     * Add the validators to form fields instead.
     */
    @Override
    public void addValidator(Validator validator) {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns a layout that is rendered below normal form contents. This area
     * can be used for example to include buttons related to form contents.
     * 
     * @return layout rendered below normal form contents.
     */
    public Layout getFooter() {
        return (Layout) getState().getFooter();
    }

    /**
     * Sets the layout that is rendered below normal form contents. Setting this
     * to null will cause an empty HorizontalLayout to be rendered in the
     * footer.
     * 
     * @param footer
     *            the new footer layout
     */
    public void setFooter(Layout footer) {
        if (getFooter() != null) {
            getFooter().setParent(null);
        }
        if (footer == null) {
            footer = new HorizontalLayout();
        }

        getState().setFooter(footer);
        footer.setParent(this);

        // Hierarchy has changed so we need to repaint (this could be a
        // hierarchy repaint only)
        requestRepaint();

    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (getParent() != null && !getParent().isEnabled()) {
            // some ancestor still disabled, don't update children
            return;
        } else {
            getLayout().requestRepaintAll();
        }
    }

    /*
     * ACTIONS
     */

    /**
     * Gets the {@link ActionManager} responsible for handling {@link Action}s
     * added to this Form.<br/>
     * Note that Form has another ActionManager inherited from
     * {@link AbstractField}. The ownActionManager handles Actions attached to
     * this Form specifically, while the ActionManager in AbstractField
     * delegates to the containing Window (i.e global Actions).
     * 
     * @return
     */
    protected ActionManager getOwnActionManager() {
        if (ownActionManager == null) {
            ownActionManager = new ActionManager(this);
        }
        return ownActionManager;
    }

    @Override
    public void addActionHandler(Handler actionHandler) {
        getOwnActionManager().addActionHandler(actionHandler);
    }

    @Override
    public void removeActionHandler(Handler actionHandler) {
        if (ownActionManager != null) {
            ownActionManager.removeActionHandler(actionHandler);
        }
    }

    /**
     * Removes all action handlers
     */
    public void removeAllActionHandlers() {
        if (ownActionManager != null) {
            ownActionManager.removeAllActionHandlers();
        }
    }

    @Override
    public <T extends Action & com.vaadin.event.Action.Listener> void addAction(
            T action) {
        getOwnActionManager().addAction(action);
    }

    @Override
    public <T extends Action & com.vaadin.event.Action.Listener> void removeAction(
            T action) {
        if (ownActionManager != null) {
            ownActionManager.removeAction(action);
        }
    }

    @Override
    public Iterator<Component> iterator() {
        return getComponentIterator();
    }

    /**
     * Modifiable and Serializable Iterator for the components, used by
     * {@link Form#getComponentIterator()}.
     */
    private class ComponentIterator implements Iterator<Component>,
            Serializable {

        int i = 0;

        @Override
        public boolean hasNext() {
            if (i < getComponentCount()) {
                return true;
            }
            return false;
        }

        @Override
        public Component next() {
            if (!hasNext()) {
                return null;
            }
            i++;
            if (i == 1) {
                return getLayout() != null ? getLayout() : getFooter();
            } else if (i == 2) {
                return getFooter();
            }
            return null;
        }

        @Override
        public void remove() {
            if (i == 1) {
                if (getLayout() != null) {
                    setLayout(null);
                    i = 0;
                } else {
                    setFooter(null);
                }
            } else if (i == 2) {
                setFooter(null);
            }
        }
    }

    @Override
    public Iterator<Component> getComponentIterator() {
        return new ComponentIterator();
    }

    public int getComponentCount() {
        int count = 0;
        if (getLayout() != null) {
            count++;
        }
        if (getFooter() != null) {
            count++;
        }

        return count;
    }

    @Override
    public boolean isComponentVisible(Component childComponent) {
        return true;
    };
}