Update feature attributes in an online feature service.

Use case
Online feature services can be updated with new data. This is useful for updating existing data in real time while working in the field.
How to use the sample
To change the feature’s damage property, tap the feature to select it, and update the damage type using the drop down.
How it works
- Create a
ServiceFeatureTableobject from a URL.- When the table loads, you can get the domain to determine which options to present in your UI.
- Create a
FeatureLayerobject from theServiceFeatureTable. - Select features from the
FeatureLayer. - To update the feature’s attribute, first load it, then use the
attributeValue. - Update the table with
updateFeatureAsync. - After a change, apply the changes on the server using
applyEditsAsync.
Relevant API
- ArcGISFeature
- FeatureLayer
- ServiceFeatureTable
Tags
amend, attribute, details, edit, editing, information, value
Sample Code
// [WriteFile Name=UpdateAttributesFeatureService, Category=EditData]// [Legal]// Copyright 2016 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
// sample headers#include "UpdateAttributesFeatureService.h"
// ArcGIS Maps SDK headers#include "ArcGISFeature.h"#include "AttributeListModel.h"#include "Basemap.h"#include "CalloutData.h"#include "Envelope.h"#include "Feature.h"#include "FeatureEditResult.h"#include "FeatureIterator.h"#include "FeatureLayer.h"#include "FeatureQueryResult.h"#include "IdentifyLayerResult.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MapViewTypes.h"#include "Point.h"#include "QueryParameters.h"#include "ServiceFeatureTable.h"#include "SpatialReference.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QMouseEvent>#include <QUrl>#include <QUuid>
using namespace Esri::ArcGISRuntime;
namespace{ // Convenience RAII struct that deletes all pointers in given container. struct FeatureEditListResultLock { FeatureEditListResultLock(const QList<FeatureEditResult*>& list) : results(list) { } ~FeatureEditListResultLock() { qDeleteAll(results); } const QList<FeatureEditResult*>& results; };}
UpdateAttributesFeatureService::UpdateAttributesFeatureService(QQuickItem* parent) : QQuickItem(parent){}
UpdateAttributesFeatureService::~UpdateAttributesFeatureService() = default;
void UpdateAttributesFeatureService::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<UpdateAttributesFeatureService>("Esri.Samples", 1, 0, "UpdateAttributesFeatureServiceSample"); qmlRegisterUncreatableType<CalloutData>("Esri.Samples", 1, 0, "CalloutData", "CalloutData is an uncreatable type");}
void UpdateAttributesFeatureService::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);
// create a Map by passing in the Basemap m_map = new Map(BasemapStyle::ArcGISStreets, this); m_map->setInitialViewpoint(Viewpoint(Point(-10800000, 4500000, SpatialReference(102100)), 3e7));
// set map on the map view m_mapView->setMap(m_map);
// create the ServiceFeatureTable m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0"), this);
// create the FeatureLayer with the ServiceFeatureTable and add it to the Map m_featureLayer = new FeatureLayer(m_featureTable, this); m_map->operationalLayers()->append(m_featureLayer);
connectSignals();}
void UpdateAttributesFeatureService::connectSignals(){ // connect to the mouse clicked signal on the MapQuickView connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // first clear the selection m_featureLayer->clearSelection();
// set the properties for qml emit hideWindow();
// call identify on the map view m_mapView->identifyLayerAsync(m_featureLayer, mouseEvent.position(), 5, false, 1).then(this, [this](IdentifyLayerResult* identifyResult) { onIdentifyLayerCompleted_(identifyResult); }); });
// connect to the viewpoint changed signal on the MapQuickView connect(m_mapView, &MapQuickView::viewpointChanged, this, [this]() { m_featureLayer->clearSelection(); emit hideWindow(); });}
void UpdateAttributesFeatureService::updateSelectedFeature(QString fieldVal){ // If the last connection is still hanging around we want to ensure it is disconnected. disconnect(m_featureLoadStatusChangedConnection);
// connect to load status changed signal, remember the connection so we can kill it once // the slot has invoked. m_featureLoadStatusChangedConnection = connect( m_selectedFeature, &ArcGISFeature::loadStatusChanged, this, [this, fieldVal](LoadStatus) { if (m_selectedFeature->loadStatus() == LoadStatus::Loaded) { // The conenction is invoked so we now forget all about this connection after this point. disconnect(m_featureLoadStatusChangedConnection);
// update the select feature's attribute value m_selectedFeature->attributes()->replaceAttribute("typdamage", fieldVal);
// update the feature in the feature table m_featureTable->updateFeatureAsync(m_selectedFeature).then(this, [this]() { m_featureTable->applyEditsAsync().then(this, [this](const QList<FeatureEditResult*>& featureEditResults) { onApplyEditsCompleted_(featureEditResults); }); }); } } );
// load selecte feature m_selectedFeature->load();}
QString UpdateAttributesFeatureService::featureType() const{ return m_featureType;}
void UpdateAttributesFeatureService::onIdentifyLayerCompleted_(IdentifyLayerResult* identifyResult){ if (!identifyResult) return;
if (!identifyResult->geoElements().empty()) { // select the item in the result m_featureLayer->selectFeature(static_cast<Feature*>(identifyResult->geoElements().at(0))); // Update the parent so the featureLayer is not deleted when the identifyResult is deleted. m_featureLayer->setParent(this);
// obtain the selected feature with attributes QueryParameters queryParams; QString whereClause = "objectid=" + identifyResult->geoElements().at(0)->attributes()->attributeValue("objectid").toString(); queryParams.setWhereClause(whereClause); m_featureTable->queryFeaturesAsync(queryParams).then(this, [this](FeatureQueryResult* featureQueryResult) { onQueryFeaturesCompleted_(featureQueryResult); }); }}
void UpdateAttributesFeatureService::onQueryFeaturesCompleted_(FeatureQueryResult* featureQueryResult){ if (featureQueryResult && featureQueryResult->iterator().hasNext()) { // first delete if not nullptr if (m_selectedFeature) delete m_selectedFeature;
// set selected feature member m_selectedFeature = static_cast<ArcGISFeature*>(featureQueryResult->iterator().next(this)); m_selectedFeature->setParent(this); m_featureType = m_selectedFeature->attributes()->attributeValue("typdamage").toString(); m_mapView->calloutData()->setTitle(QString("<br><font size=\"+2\"><b>%1</b></font>").arg(m_featureType)); m_mapView->calloutData()->setLocation(m_selectedFeature->geometry().extent().center()); emit featureTypeChanged(); emit featureSelected(); }}
void UpdateAttributesFeatureService::onApplyEditsCompleted_(const QList<FeatureEditResult*>& featureEditResults){ // Lock is a convenience wrapper that deletes the contents of featureEditResults when we leave scope. FeatureEditListResultLock lock(featureEditResults);
// check if result list is not empty if (!lock.results.isEmpty()) { // obtain the first item in the list FeatureEditResult* featureEditResult = lock.results.first(); // check if there were errors, and if not, log the new object ID if (!featureEditResult->isCompletedWithErrors()) qDebug() << "Successfully updated attribute for Object ID:" << featureEditResult->objectId(); else qDebug() << "Apply edits error."; } m_featureLayer->clearSelection();}// [WriteFile Name=UpdateAttributesFeatureService, Category=EditData]// [Legal]// Copyright 2016 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]
#ifndef UPDATE_ATTRIBUTES_FEATURE_SERVICE_H#define UPDATE_ATTRIBUTES_FEATURE_SERVICE_H
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{ class Map; class MapQuickView; class FeatureLayer; class ServiceFeatureTable; class ArcGISFeature; class IdentifyLayerResult; class FeatureQueryResult; class FeatureEditResult;}
class QString;
class UpdateAttributesFeatureService : public QQuickItem{ Q_OBJECT
Q_PROPERTY(QString featureType READ featureType NOTIFY featureTypeChanged)
public: explicit UpdateAttributesFeatureService(QQuickItem* parent = nullptr); ~UpdateAttributesFeatureService() override;
void componentComplete() override; static void init(); Q_INVOKABLE void updateSelectedFeature(QString fieldVal);
signals: void featureSelected(); void featureTypeChanged(); void hideWindow();
private: void onIdentifyLayerCompleted_(Esri::ArcGISRuntime::IdentifyLayerResult* identifyResult); void onQueryFeaturesCompleted_(Esri::ArcGISRuntime::FeatureQueryResult* featureQueryResult); void onApplyEditsCompleted_(const QList<Esri::ArcGISRuntime::FeatureEditResult*>& featureEditResults); void connectSignals(); QString featureType() const;
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_featureLayer = nullptr; Esri::ArcGISRuntime::ServiceFeatureTable* m_featureTable = nullptr; Esri::ArcGISRuntime::ArcGISFeature* m_selectedFeature = nullptr; QString m_featureType; QMetaObject::Connection m_featureLoadStatusChangedConnection;};
#endif // UPDATE_ATTRIBUTES_FEATURE_SERVICE_H// [WriteFile Name=UpdateAttributesFeatureService, Category=EditData]// [Legal]// Copyright 2016 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 QtQuickimport QtQuick.Controlsimport QtQuick.Layoutsimport Esri.Samplesimport Esri.ArcGISRuntime.Toolkit
UpdateAttributesFeatureServiceSample { id: updateFeaturesSample width: 800 height: 600
readonly property var featAttributes: ["Destroyed", "Major", "Minor", "Affected", "Inaccessible"]
// add a mapView component MapView { id: mapView anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Callout { id: callout background: Rectangle { border.width: 1; border.color: "lightgrey" } calloutData: mapView.calloutData leaderPosition: Callout.LeaderPosition.Automatic onAccessoryButtonClicked: { updateWindow.visible = true; } } }
onFeatureSelected: { // show the callout callout.showCallout();
// set the combo box's default value damageComboBox.currentIndex = featAttributes.indexOf(updateFeaturesSample.featureType); }
onHideWindow: { // hide the callout if (callout.visible) callout.dismiss(); // hide the update window updateWindow.visible = false; }
// Update Window Rectangle { id: updateWindow width: childrenRect.width height: childrenRect.height anchors.centerIn: parent radius: 10 visible: false
MouseArea { anchors.fill: parent onClicked: mouse => mouse.accepted = true; onWheel: wheel => wheel.accepted = true; }
GridLayout { columns: 2 anchors.margins: 5
Text { Layout.columnSpan: 2 Layout.margins: 5 text: "Update Attribute" font.pixelSize: 16 }
ComboBox { property int modelWidth: 0 Layout.minimumWidth: modelWidth + leftPadding + rightPadding + (indicator ? indicator.width : 10) Layout.columnSpan: 2 Layout.margins: 5 Layout.fillWidth: true id: damageComboBox model: featAttributes Component.onCompleted : { for (let i = 0; i < model.length; ++i) { metrics.text = model[i]; modelWidth = Math.max(modelWidth, metrics.width); } } TextMetrics { id: metrics font: damageComboBox.font } }
Button { Layout.margins: 5 text: "Update" // once the update button is clicked, hide the windows, and fetch the currently selected features onClicked: { if (callout.visible) callout.dismiss(); updateWindow.visible = false; updateFeaturesSample.updateSelectedFeature(damageComboBox.currentText) } }
Button { Layout.alignment: Qt.AlignRight Layout.margins: 5 text: "Cancel" // once the cancel button is clicked, hide the window onClicked: updateWindow.visible = false; } } }}// [Legal]// Copyright 2015 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]
// sample headers#include "UpdateAttributesFeatureService.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>#include <QSettings>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("Update Attributes Feature Service"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample UpdateAttributesFeatureService::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive); #endif
// Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
Esri::ArcGISRuntime::Toolkit::registerComponents(*(view.engine()));
// Set the source view.setSource(QUrl("qrc:/Samples/EditData/UpdateAttributesFeatureService/UpdateAttributesFeatureService.qml"));
view.show();
return app.exec();}