Add features with contingent values

View inQMLC++
View on GitHub
Sample viewer app

Create and add features whose attribute values satisfy a predefined set of contingencies.

screenshot

Use case

Contingent values are a data design feature that allow you to make values in one field dependent on values in another field. Your choice for a value on one field further constrains the domain values that can be placed on another field. In this way, contingent values enforce data integrity by applying additional constraints to reduce the number of valid field inputs.

For example, a field crew working in a sensitive habitat area may be required to stay a certain distance away from occupied bird nests, but the size of that exclusion area differs depending on the bird's level of protection according to presiding laws. Surveyors can add points of bird nests in the work area and their selection of the size of the exclusion area will be contingent on the values in other attribute fields.

How to use the sample

Tap on the map to add a feature symbolizing a bird's nest. Then choose values describing the nest's status, protection, and buffer size. Notice how different values are available depending on the values of preceding fields. Once the contingent values are validated, tap "Save" to add the feature to the map.

How it works

  1. Create and load a Geodatabase.
  2. Load the "BirdNests" GeodatabaseFeatureTable.
  3. Load the ContingentValuesDefinition from the feature table.
  4. Create a new FeatureLayer from the feature table and add it to the map.
  5. Create a new Feature from the feature table using FeatureTable.createFeatureWithAttributes
  6. Supply the initial list of selections. This can also be retrieved from the FeatureTable's Field's CodedValueDomain
  7. After making the initial selection, retrieve the valid contingent values for each field as you select the values for the attributes.

i. Create a ContingentValuesResult from FeatureTable.contingentValues and pass in the current feature and the target field by name. ii. Get a list of valid ContingentValues from ContingentValuesResult.contingentValuesByFieldGroup with the name of the relevant field group. iii. Loop through the list to create a list of ContingentCodedValue names or the minimum and maximum values of a ContingentRangeValue depending on the type of ContingentValue returned. 8. Validate the new feature's contingent values by creating a list of ContingencyConstrantViolations by passing the new feature to FeatureTable.validateContingencyConstraints. If the list is empty, then it is valid and can be saved to the map.

Relevant API

  • ContingencyConstraintViolation
  • ContingentCodedValue
  • ContingentRangeValue
  • ContingentValuesDefinition
  • ContingentValuesResult
  • Geodatabase
  • GeodatabaseFeatureTable

Offline Data

To set up the sample's offline data, see the Use offline data in the samples section of the Qt Samples repository overview.

Link Local Location
Contingent Values Bird Nests <userhome>/ArcGIS/Runtime/Data/geodatabase/ContingentValuesBirdNests.geodatabase
Fillmore topographic map <userhome>/ArcGIS/Runtime/Data/vtpk/FillmoreTopographicMap.vtpk

About the data

The mobile geodatabase contains birds nests in the Fillmore area, defined with contingent values. Each feature contains information about its status, protection, and buffer size.

Additional information

Learn more about contingent values and how to utilize them on the ArcGIS Pro documentation.

Tags

coded values, contingent values, feature table, geodatabase, range values

Sample Code

ContingentValues.qml
Use dark colors for code blocksCopy
                                                                                                                                                                                                                                                                                                                                                                           
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
// [WriteFile Name=ContingentValues, Category=EditData]
// [Legal]
// Copyright 2022 Esri.

// 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.
// [Legal]

import QtQuick 2.12
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import Esri.ArcGISRuntime 100.15
import Esri.ArcGISExtras 1.1


Rectangle {
    id: sampleWindow
    clip: true
    width: 800
    height: 600

    readonly property url dataPath: System.userHomePath + "/ArcGIS/Runtime/Data/"

    // Feature to define attributes for with ContingentValues
    property var newFeature: null;

    // TaskId to track the queryFeatures() function of the GeodatabaseFeatureTable
    property var taskId;

    // GeodatabaseFeatureTable
    property var birdNestsTable: null;

    // Field Domains are hardcoded to simplify this sample, but can be obtained from a FeatureTable's Domain
    property var statusValues: {"Occupied":"OCCUPIED", "Unoccupied":"UNOCCUPIED"};
    property var protectionValues: {"Endangered":"ENDANGERED", "Not endangered":"NOT_ENDANGERED", "N/A":"NA"};

    MapView {
        id: mapView
        anchors.fill: parent

        MouseArea {
            anchors.fill: parent
            visible: attributePrompt.visible
            onClicked: mouse.accepted = !attributePrompt.visible
            onWheel:  wheel.accepted = !attributePrompt.visible
        }

        Component.onCompleted: {
            // Set and keep the focus on MapView to enable keyboard navigation
            forceActiveFocus();
        }

        Map {
            Basemap {
                ArcGISVectorTiledLayer {
                    url: dataPath + "vtpk/FillmoreTopographicMap.vtpk"
                }
            }

            ViewpointCenter {
                Point {
                    x: -13236000
                    y: 4081200
                    spatialReference: SpatialReference { wkid: 3857 }
                }
                targetScale: 8822
            }

            FeatureLayer {
                id: nestsLayer
                featureTable: birdNestsTable ?? null;

                Geodatabase {
                    id: gdb
                    path: dataPath + "geodatabase/ContingentValuesBirdNests.geodatabase"

                    onLoadStatusChanged: {
                        if (loadStatus === Enums.LoadStatusLoaded) {
                            birdNestsTable = gdb.geodatabaseFeatureTablesByTableName["BirdNests"];
                            birdNestsTable.load();
                        }
                    }
                }

                onLoadStatusChanged: {
                    if (nestsLayer.loadStatus === Enums.LoadStatusLoaded) {
                        // Load the ContingentValuesDefinition to enable access to the GeodatabaseFeatureTable's ContingentValues data such as FieldGroups and ContingentValuesResults
                        birdNestsTable.contingentValuesDefinition.load();

                        // Load map with initial nest buffers showing
                        bufferFeatures();
                    }
                }
            }
        }

        GraphicsOverlay {
            id: bufferGraphicsOverlay
            renderer: SimpleRenderer {
                SimpleFillSymbol {
                    style: Enums.SimpleFillSymbolStyleForwardDiagonal
                    color: "red"
                    outline: SimpleLineSymbol {
                        style: Enums.SimpleLineSymbolStyleSolid
                        color: "black"
                        width: 2
                    }
                }
            }
        }

        onMouseClicked: {
            // Open attribute prompt and create a new feature for editing
            attributePrompt.visible = true;
            newFeature = birdNestsTable.createFeatureWithAttributes({}, mouse.mapPoint);
            birdNestsTable.addFeature(newFeature);
        }
    }


    Control {
        id: attributePrompt
        anchors {
            top: sampleWindow.top
            right: sampleWindow.right
            margins: 5
        }

        background: Rectangle {
            color: "#fdfdfd"
        }

        visible: false

        contentItem: Column {
            id: inputColumn
            spacing: 5
            padding: 10

            Text {
                text: "Status"
                font {
                    bold: true
                    pointSize: 11
                }
            }

            ComboBox {
                id: statusComboBox

                // This ComboBox is hardcoded, but can be dynamically obtained from the feature layer's field's domain values
                model: ["", "Occupied", "Unoccupied"]

                onCurrentValueChanged: {
                    if (statusComboBox.currentValue === "") {
                        protectionComboBox.model = [""];
                        return;
                    }

                    // Update the feature's attribute map with the selection
                    newFeature.attributes.replaceAttribute("Status", statusValues[statusComboBox.currentValue]);

                    // Append the valid contingent coded values to the subsequent ComboBox
                    protectionComboBox.model = [""].concat(getContingentValues("Protection", "ProtectionFieldGroup"));
                }
            }

            Text {
                text: "Protection"
                font {
                    bold: true
                    pointSize: 11
                }
            }

            ComboBox {
                id: protectionComboBox
                model: [""];

                enabled: statusComboBox.currentText !== ""

                onCurrentValueChanged: {
                    if (protectionComboBox.currentValue === "")
                        return;

                    // Update the feature's attribute map with the selection
                    newFeature.attributes.replaceAttribute("Protection", protectionValues[protectionComboBox.currentValue]);

                    // Get the valid contingent range values for the subsequent SpinBox
                    const minMax = getContingentValues("BufferSize", "BufferSizeFieldGroup")

                    // If getContingentValues() returned results, update the spin box values
                    if (minMax[0] !== "") {
                        rangeValuesSpinBox.from = minMax[0];
                        rangeValuesSpinBox.to = minMax[1];

                        // Explicitly set the buffer size to the rangeValuesSpinBox value in case onValueChanged doesn't trigger
                        newFeature.attributes.replaceAttribute("BufferSize", rangeValuesSpinBox.value);
                        saveButton.enabled = validateContingentValues();
                    }
                }
            }

            Text {
                text: "Buffer Size"
                font {
                    bold: true
                    pointSize: 11
                }
            }

            Text {
                text: rangeValuesSpinBox.from + " to " + rangeValuesSpinBox.to;
            }

            SpinBox {
                id: rangeValuesSpinBox
                editable: true
                from: 0;
                to: 0;
                stepSize: 10
                value: 0;

                enabled: protectionComboBox.currentText !== ""

                onValueChanged: {
                    if (protectionComboBox.currentValue === "")
                        return;

                    newFeature.attributes.replaceAttribute("BufferSize", rangeValuesSpinBox.value);

                    // Validate that all contingencies are valid, if so, enable the save button
                    saveButton.enabled = validateContingentValues();
                }
            }

            Button {
                id: saveButton
                Text {
                    anchors.fill: parent
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    text: "Save"
                }

                enabled: false

                onClicked: {
                    const valid = validateContingentValues();
                    if (validateContingentValues()) {
                        birdNestsTable.updateFeature(newFeature);
                        bufferFeatures();
                        attributePrompt.visible = false;
                    }
                }
            }

            Button {
                id: discardButton
                Text {
                    anchors.fill: parent
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    text: "Discard"
                }
                onClicked: {
                    birdNestsTable.deleteFeature(newFeature);
                    attributePrompt.visible = false
                }
            }
        }

        onVisibleChanged: {
            if (!visible)
                return;

            // Reset attribute panel values when the panel opens
            statusComboBox.currentIndex = 0;
            protectionComboBox.currentIndex = 0;
            rangeValuesSpinBox.from = 0;
            rangeValuesSpinBox.to = 0;
        }
    }

    function getContingentValues(field, fieldGroup) {
        const contingentValuesResult = birdNestsTable.contingentValues(newFeature, field);
        const contingentValuesList = contingentValuesResult.contingentValuesByFieldGroup[fieldGroup];

        const returnList = [];

        contingentValuesList.forEach(contingentValue => {
                                         if (contingentValue.objectType === Enums.ContingentValueTypeContingentCodedValue) {
                                             returnList.push(contingentValue.codedValue.name);
                                         } else if (contingentValue.objectType === Enums.ContingentValueTypeContingentRangeValue) {
                                             returnList.push(contingentValue.minValue);
                                             returnList.push(contingentValue.maxValue);
                                         }
                                     });
        return returnList;
    }

    function validateContingentValues() {
        const contingencyConstraintsList = birdNestsTable.validateContingencyConstraints(newFeature);

        if (contingencyConstraintsList.length === 0)
            return true;

        return false;
    }

    QueryParameters {
        id: bufferParameters
        whereClause: "BufferSize > 0"
    }

    // This function creates a buffer around nest features based on their BufferSize value
    // It is included to demonstrate the sample use case
    function bufferFeatures() {
        const featureStatusChanged = ()=> {
            switch (birdNestsTable.queryFeaturesStatus) {
                case Enums.TaskStatusCompleted:
                birdNestsTable.queryFeaturesStatusChanged.disconnect(featureStatusChanged);
                bufferGraphicsOverlay.graphics.clear();

                const result = birdNestsTable.queryFeaturesResults[taskId];
                if (result) {
                    const features = Array.from(result.iterator.features);
                    features.forEach(feature => {
                                         const buffer = GeometryEngine.buffer(feature.geometry, feature.attributes.attributeValue("BufferSize"));
                                         const bufferGraphic = ArcGISRuntimeEnvironment.createObject("Graphic", {geometry: buffer});
                                         bufferGraphicsOverlay.graphics.append(bufferGraphic);
                                     });
                } else {
                    console.log("The query finished but there was no result for this taskId");
                }
                break;

                case Enums.TaskStatusErrored:
                birdNestsTable.queryFeaturesStatusChanged.disconnect(featureStatusChanged);
                if (birdNestsTable.error) {
                    console.log("Feature query error", birdNestsTable.error.message, birdNestsTable.error.additionalMessage);
                } else {
                    console.log("The query encountered an error, but provided no error message");
                }
                break;

                default:
                break;
            }
        }

        birdNestsTable.queryFeaturesStatusChanged.connect(featureStatusChanged);
        taskId = birdNestsTable.queryFeatures(bufferParameters);
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.