2

I am working on a model where I need some calculations on only some selected features.

In the normal fieldcalculator you can check 'only update ... selected features'. When using the fieldcalculator from the processing toolbox, it is not possible to do that.

Is there a workaround to fix this?

4

If you select your features before running the Field Calculator in the modeler, the output will contain only those selected features.

A workaround would be to use a custom script in your model which allows you to update your selected features within the same layer.

To do this, go to Processing Toolbox > Scripts > Tools > Create new script and copy the following:

##Update selection=name
##Layer=vector
##Fields=Field Layer
##Formula=string

from qgis.core import QgsExpression

layer = processing.getObject(Layer)  
layer.startEditing()

idx = layer.fieldNameIndex(Fields)
e = QgsExpression(Formula)
e.prepare(layer.pendingFields())

for f in layer.selectedFeatures():
    f[idx] = e.evaluate(f)
    layer.updateFeature( f )

layer.commitChanges()

Save the script into C:\Users\You\.qgis2\processing\scripts. In your modeler, create 3 parameters:

  • Layer - Vector layer
  • Field - Table field
  • Formula - String

Then add the custom script from the list of algorithms and fill in the options:

Update selection


I ran a test on a layer where I want to change the values in the id field for the selected features:

Attributes

I ran the model selecting the layer, field and entering a value of 100:

Running model

Once finished, the attributes of the layer should be updated:

Attributes result

Note that you could use the same expressions as you would in the Field Calculator such as CASE statements etc. due to the QgsExpression class used in the script.

  • 1
    Thanks. I am not familiar with python but I trie it out. – PieterB Jan 18 '16 at 8:37
  • @PieterB - Most welcome buddy! Hope it works for you :) – Joseph Jan 18 '16 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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