More

Filling fields with conditional clauses


I have four fields in my shapefile. I would like to fill only one of them (cell of attribute table) and automatically after to write one cell the others one will be filled by conditional clause. I need that this conditional has to keep there, filling the value attribute, without necessary to run filed calculator (automatically).


You could create Virtual fields for the fields you want to have automatically updated. When you create an expression for these virtual fields, they will be applied each time you make and save changes to the shapefile (you may need to reload the attribute table to see the changes).

Also note that the you will need to create a Project for the shapefile (if you haven't done so already) as virtual fields are stored in the project files (.qgs).


Alternatively, you could also edit and run the following script from the Python Console. After you have filled out the columncodigo, changeformula_1etc. to your desired expression and run it. You should get the same results as you would from using virtual fields with the main difference being that the fields are stored within the shapefile (useful if you need to export results):

layer = qgis.utils.iface.activeLayer() layer.startEditing() idx_1 = layer.fieldNameIndex( "nivel_1" ) idx_2 = layer.fieldNameIndex( "nivel_2" ) idx_3 = layer.fieldNameIndex( "nivel_3" ) formula_1 = 'case when "codigo" = 1 then 1 end' formula_2 = 'case when "codigo" = 2 then 2 end' formula_3 = 'case when "codigo" = 3 then 3 end' e_1 = QgsExpression( formula_1 ) e_2 = QgsExpression( formula_2 ) e_3 = QgsExpression( formula_3 ) e.prepare(layer.pendingFields()) for f in layer.getFeatures(): f[idx_1] = e_1.evaluate( f ) f[idx_2] = e_2.evaluate( f ) f[idx_3] = e_3.evaluate( f ) layer.updateFeature( f ) layer.commitChanges()

Note: There are nicer ways of scripting to achieve this!


Hope this helps!