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).

I will fill only one of the field: "nivel_1", "nivel_2", "nivel_3" and "codigo" and the others are fielded  immediatly

  • Are you looking for if field_a == 'foo' then field_b = 'new stuff'?
    – dassouki
    Oct 16, 2015 at 19:35
  • Yes. But I need to do it many time in when I am editing. I would like to put one script that do it without necessary run field calculator. Oct 16, 2015 at 19:37

1 Answer 1


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).

Virtual field

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 column codigo, change formula_1 etc. 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()

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 )


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 )


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

Hope this helps!

  • 1
    @diogo-caribé To bring the best of both worlds, you could use the AutoFields plugin, which allows you to set a CASE (if) expression, calculates the values automatically after feature editing, and stores them into your Shapefile. Aug 19, 2016 at 22:55
  • 1
    @GermánCarrillo - That is one very nice plugin!
    – Joseph
    Aug 25, 2016 at 11:54

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.