2

I can't figure how to do that, here is my code :

auxKeyField = myLayer.fields().field(myLayer.fields().indexOf('id'))
auxStorage = QgsProject.instance().auxiliaryStorage()
myAuxLayer = auxStorage.createAuxiliaryLayer(auxKeyField, myLayer)
myLayer.setAuxiliaryLayer(myAuxLayer)

propAux = QgsPropertyDefinition()
propAux.setName('auxfield')
propAux.setDataType(QgsPropertyDefinition.DataTypeNumeric)
res = myAuxLayer.addAuxiliaryField(propAux)
auxLayerFields = myAuxLayer.fields()

auxFeature = QgsVectorLayerUtils.createFeature(myAuxLayer)
auxFeature.setAttribute('ASPK', 1)
auxFeature.setAttribute('_auxfield', 123)
res = myAuxLayer.addFeature(auxFeature)

myAuxLayer.save()

Auxiliary field is created, addFeature returns true, the auxiliary field column appears in attribute table, but it contains only NULL values, even for id=1.

EDIT 1 : Adding myLayer.startEditing() at the beginning of the code, adding myLayer.commitChanges() at the end, and removing myAuxLayer.save() seemed to solve the problem. Unfortunately, as soon as I save the project, every value in the auxiliary field disappears...

EDIT 2 : Looking at unit tests I ended up with this code :

auxKeyField = myLayer.fields().field(myLayer.fields().indexOf('id'))
auxStorage = QgsProject.instance().auxiliaryStorage()
myAuxLayer = auxStorage.createAuxiliaryLayer(auxKeyField, myLayer)
myLayer.setAuxiliaryLayer(myAuxLayer)

propAux = QgsPropertyDefinition(
    'offset',  # name
    'string',  # description
    QgsPropertyDefinition.Offset,  # type
    'symbol',  # origin
    'decalop'  # comment
)
res = myAuxLayer.addAuxiliaryField(propAux)

req = QgsFeatureRequest().setFilterExpression('id=1')
myFeature = QgsFeature()
myLayer.getFeatures(req).nextFeature(myFeature )
auxFieldName = QgsAuxiliaryLayer.nameFromProperty(propAux, True)
index = myLayer.fields().indexOf(auxFieldName)
myLayer.changeAttributeValue(myFeature.id(), index, 123)

Sadly, every value in the auxiliary field still disappear as soon as I save the project...

1 Answer 1

1

It turns out that it didn't work because myLayer was a virtual layer, referencing a WFS source. Changing it to a straight WFS layer made it work like a charm, with second version of code (EDIT 2)...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.