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?
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).:
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:
Setting and running the model:
Result:
No comments:
Post a Comment