TransWikia.com

How to connect input parameter to the field calculator algorithm within the graphical modeler?

Geographic Information Systems Asked by Eleftheria on July 15, 2021

I am building a model in the graphical modeler of QGIS 2.8.1 Wien and I would like to give the option to the user to enter a number in the model with which a selected field will be multiplied, but I cannot figure out how to connect the parameter for the user input to the field calculator algorithm.

Any ideas on this?

One Answer

Instead of using the Field Calculator tool, a possible workaround is to create a custom script which allows the user to choose an attribute field and update it with a value they enter.

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

##Update field by number=name
##Layer=vector
##Fields=Field Layer
##Number=number 0

from qgis.core import QgsExpression

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

idx = layer.fieldNameIndex(Fields)
n = str(Number)
i = str(Fields)
e = QgsExpression(n + '*' + i)
e.prepare(layer.pendingFields())

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

layer.commitChanges()

Save the script into C:/Users/You/.qgis2/processing/scripts. You will need 3 parameters:

  • Layer - Vector layer
  • Field - Table field
  • Number - Number

Then add the script from the list of algorithms to your model. Use the Parent algorithms option if you want this script to run after a specific tool (i.e. at the end of the model).:

Model


Did a simple test where I want to update the id field by entering 5 in the Number parameter. Here is the attribute table initially:

Original attributes

Setting and running the model:

Setting model

Result:

Result

Correct answer by Joseph on July 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP