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::createFeature
  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.cppContingentValues.cppContingentValues.hContingentValues.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
// [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]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

#include "ContingentValues.h"

#include "ArcGISVectorTiledLayer.h"
#include "CodedValueDomain.h"
#include "ContingentCodedValue.h"
#include "ContingentRangeValue.h"
#include "ContingentValuesDefinition.h"
#include "ContingentValuesResult.h"
#include "FeatureLayer.h"
#include "Geodatabase.h"
#include "GeodatabaseFeatureTable.h"
#include "GeometryEngine.h"
#include "Map.h"
#include "MapQuickView.h"
#include "SimpleFillSymbol.h"
#include "SimpleLineSymbol.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleRenderer.h"

#include <QDir>

#ifdef Q_OS_IOS
#include <QStandardPaths>
#endif // Q_OS_IOS

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
  QString dataPath;

#ifdef Q_OS_ANDROID
  dataPath = "/sdcard";
#elif defined Q_OS_IOS
  dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
  dataPath = QDir::homePath();
#endif

  return dataPath;
}
}

ContingentValues::ContingentValues(QObject* parent /* = nullptr */):
  QObject(parent)
{
  // Load the basemap from a vector tile package
  const QString vtpkDataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/vtpk/FillmoreTopographicMap.vtpk";
  ArcGISVectorTiledLayer* fillmoreVTPK = new ArcGISVectorTiledLayer(QUrl::fromLocalFile(vtpkDataPath), this);
  Basemap* fillmoreBasemap = new Basemap(fillmoreVTPK, this);
  m_map = new Map(fillmoreBasemap, this);

  // Load the geodatabase from a mobile geodatabase
  const QString gdbDataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/geodatabase/ContingentValuesBirdNests.geodatabase";
  m_geodatabase = new Geodatabase(gdbDataPath, this);

  // The coded value domains in this sample are hardcoded for simplicity, but can be retrieved from the GeodatabaseFeatureTable's Field's Domains.
  m_statusValues = QVariantMap{{"Occupied", "OCCUPIED"}, {"Unoccupied", "UNOCCUPIED"}};
  m_protectionValues = QVariantMap{{"Endangered", "ENDANGERED"}, {"Not endangered", "NOT_ENDANGERED"}, {"N/A", "NA"}};
}

ContingentValues::~ContingentValues() = default;

void ContingentValues::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<ContingentValues>("Esri.Samples", 1, 0, "ContingentValuesSample");
}

MapQuickView* ContingentValues::mapView() const
{
  return m_mapView;
}

// Set the view with a graphics overlay
void ContingentValues::setMapView(MapQuickView* mapView)
{
  if (!mapView || mapView == m_mapView)
    return;

  m_mapView = mapView;

  m_mapView->setMap(m_map);
  m_mapView->setViewpoint(Viewpoint(Point(-13236000, 4081200), 8822));

  // Create the graphics overlay with which to display the nest buffer exclusion areas
  m_graphicsOverlay = new GraphicsOverlay(this);
  Symbol* bufferSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::ForwardDiagonal, Qt::red, new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::black, 2, this), this);
  m_graphicsOverlay->setRenderer(new SimpleRenderer(bufferSymbol, this));
  m_mapView->graphicsOverlays()->append(m_graphicsOverlay);

  createConnections();
  m_geodatabase->load();

  emit mapViewChanged();
}

// Load the Geodatabase, GeodatabaseFeatureTable, and the ContingentValuesDefinition
void ContingentValues::createConnections()
{
  connect(m_geodatabase, &Geodatabase::doneLoading, this, [this]()
  {
    // Retrieve the "BirdNests" geodatabaseFeatureTable which contains the ContingentValuesDefinition, among other important member variables and functions
    m_gdbFeatureTable = m_geodatabase->geodatabaseFeatureTable("BirdNests");

    if (!m_gdbFeatureTable)
      return;

    connect(m_gdbFeatureTable, &GeodatabaseFeatureTable::doneLoading, this, [this]
    {
      // Load the ContingentValuesDefinition to enable access to the GeodatabaseFeatureTable's ContingentValues data such as FieldGroups and ContingentValuesResults
      m_gdbFeatureTable->contingentValuesDefinition()->load();

      // Load and display the mobile geodatabase's predefined bird nests on the map
      FeatureLayer* nestLayer = new FeatureLayer(m_gdbFeatureTable, this);
      m_map->operationalLayers()->append(nestLayer);

      queryAndBufferFeatures();
    });

    connect(m_gdbFeatureTable, &GeodatabaseFeatureTable::queryFeaturesCompleted, this, &ContingentValues::bufferFeaturesFromQueryResults);

    m_gdbFeatureTable->load();
  });

  connect(m_mapView, &MapQuickView::mouseClicked, this, &ContingentValues::createNewEmptyFeature);
}

// When the user clicks or taps on the map, instantiate a new feature and show the attribute form interface
void ContingentValues::createNewEmptyFeature(QMouseEvent mouseEvent)
{
  // Create a new empty feature to define attributes for
  m_newFeature = static_cast<ArcGISFeature*>(m_gdbFeatureTable->createFeature({}, m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y()), this));
  m_gdbFeatureTable->addFeature(m_newFeature);

  // Show the attribute form interface
  setFeatureAttributesPaneVisibe(true);
}

// Get a list of a feature's valid contingent values for field within a participating contingent value field group
QVariantList ContingentValues::getContingentValues(QString field, QString fieldGroupName)
{
  if (m_gdbFeatureTable->contingentValuesDefinition()->loadStatus() != LoadStatus::Loaded)
    return {};

  // Create an empty list with which to return the valid contingent values
  QVariantList contingentValuesNamesList = {};

  // Instantiate a dictionary containing all possible values for a field in the context of the contingent field groups it participates in
  ContingentValuesResult* contingentValuesResult = m_gdbFeatureTable->contingentValues(m_newFeature, field);

  // Loop through the contingent values. The QML UI is hardcoded to expect a list of contingent coded value names or a minimum and maximum value from a contingent range value
  for (ContingentValue* contingentValue : contingentValuesResult->contingentValuesByFieldGroup(this).value(fieldGroupName))
  {
    // Contingent coded values are contingent values defined from a coded value domain.
    // There are often multiple results returned by the ContingentValuesResult
    if (contingentValue->contingentValueType() == ContingentValueType::ContingentCodedValue)
    {
      ContingentCodedValue* contingentCodedValue = static_cast<ContingentCodedValue*>(contingentValue);
      if (contingentCodedValue)
        contingentValuesNamesList.append(contingentCodedValue->codedValue().name());
    }
    // Contingent range values constrain a range value domain
    // the ContingentValuesResult for a field defined by a range value domain often contains only one entry with a minimum and maximum value
    else if (contingentValue->contingentValueType() == ContingentValueType::ContingentRangeValue)
    {
      ContingentRangeValue* contingentRangeValue = static_cast<ContingentRangeValue*>(contingentValue);
      if (contingentRangeValue)
      {
        contingentValuesNamesList.append({contingentRangeValue->minValue()});
        contingentValuesNamesList.append({contingentRangeValue->maxValue()});
      }
    }
  }

  return contingentValuesNamesList;
}

// Validates if the sample's new feature has any constraint violations
bool ContingentValues::validateContingentValues()
{
  if (m_gdbFeatureTable->contingentValuesDefinition()->loadStatus() != LoadStatus::Loaded || !m_newFeature)
    return false;
  // Returns a list of field groups whose contingencies are in violation as well as the type of violation
  QList<ContingencyConstraintViolation*> constraintViolations = m_gdbFeatureTable->validateContingencyConstraints(m_newFeature);

  // If the list is empty, there are no violations and the attribute map satisfies all contingencies
  if (constraintViolations.isEmpty())
    return true;

  return false;
}

// Save the sample's new feature to the map's geodatabse feature table
void ContingentValues::createNewNest()
{
  // Once the attribute map is filled and validated, save the feature to the geodatabase feature table
  m_gdbFeatureTable->updateFeature(m_newFeature);

  queryAndBufferFeatures();
}

void ContingentValues::discardFeature()
{
  m_gdbFeatureTable->deleteFeature(m_newFeature);
}

// Update a specific field with a new value in the new feature's attribute map
void ContingentValues::updateField(QString field, QVariant value)
{
  if (field == "Status")
    m_newFeature->attributes()->replaceAttribute(field, m_statusValues.value(value.toString()));
  else if (field == "Protection")
    m_newFeature->attributes()->replaceAttribute(field, m_protectionValues.value(value.toString()));
  else if (field == "BufferSize")
    m_newFeature->attributes()->replaceAttribute(field, value.toInt());
  else
    qWarning() << field << "not found in any of the data dictionaries";
}

// The following two functions create a buffer around nest features based on their BufferSize value
// They are included to demonstrate the sample use case

// Kicks off a query feature task to return all features with buffer sizes greater than zero
void ContingentValues::queryAndBufferFeatures()
{
  if (!m_gdbFeatureTable || m_gdbFeatureTable->loadStatus() != LoadStatus::Loaded)
    return;

  m_graphicsOverlay->graphics()->clear();

  QueryParameters params;
  params.setWhereClause("BufferSize > 0");
  m_gdbFeatureTable->queryFeatures(params);
}

// Buffers all features from the preceeding feature query using the BufferSize field value, create graphics with the results, and adds them to the graphics overlay
void ContingentValues::bufferFeaturesFromQueryResults(QUuid, FeatureQueryResult* results)
{
  FeatureIterator iterator = results->iterator();

  while (iterator.hasNext())
  {
    Feature* feature = iterator.next(this);
    const double bufferDistance = feature->attributes()->attributeValue("BufferSize").toDouble();
    Polygon buffer = GeometryEngine::buffer(feature->geometry(), bufferDistance);
    m_mapView->graphicsOverlays()->at(0)->graphics()->append(new Graphic(buffer, this));
  }
}

bool ContingentValues::featureAttributesPaneVisibe() const
{
  return m_featureAttributesPaneVisible;
}

void ContingentValues::setFeatureAttributesPaneVisibe(bool showFeatureAttributesPane)
{
  m_featureAttributesPaneVisible = showFeatureAttributesPane;
  emit featureAttributesPaneVisibeChanged();
}

QVariantMap ContingentValues::statusValues() const
{
  return m_statusValues;
}

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