1

Is it possible to populate a number of fields in a shapefile in QGIS with different values based on the values of one other field? Essentially what I want to be able to do is to populate fields to allow export of features from a shapefile as a GeoJSON into a separate database with a number of fields populated to a certain format. So for example I enter a text value, let’s say “AA_BB” via a value map drop down in the attribute table and I want another text field to automatically enter “XXX” and two numeric fields to enter a value eg “4” and “22”. I know it’s weird but it’s to try to relate two completely different styling formats between two completely different systems. I was thinking Value Relations would maybe do it but I can’t figure out how to configure that. Anyone any suggestions? I don't know how to script.

2

Use the Field Calculator to create or update the new field.

Write an expression that achieves what you want. Using your example, write an expression like this:

case 
 when "field1" = 'AA_BB' then 'XXX'
 when "field1" = 'AA_CC' then 'XXY'
 when "field1" = 'BB_CC' then 'XYZ'


 else 'other'
end

Add as many when [condition] then [result] lines as needed to cover all the possible conditions. The else line is optional - use this to cover any conditions you didn't cover.

If you want the field to auto-populate every time you add a new feature, it must be a virtual field. Virtual fields are saved in the QGIS project file. They're not saved as part of the source data. When you export the file, be sure to choose the export option to "replace raw field values with displayed values".

Note: QGIS has a feature, auto-updating default field values, which sounds perfect for this situation. Unfortunately, the default field value expression cannot reference another field value. If you define a default field value with the expression I used above, it always comes out as 'other'. That's why I didn't use this feature here. It's a great feature if you want an auto-populating field with a calculation using the $length or $area functions though.

  • Brilliant thank you. This works although I have to run six different expressions. it's a pity it doesn't work in the default value option. I use virtual fields for other expressions as well such as area. When I try to run the $area expression in the default option is always returns the value in sqm regardless of what's set in the options. I need it to be hectares. Thanks for the help. – webg Oct 10 '19 at 9:19
  • That might be a bug, with the $area function not respecting the project settings when used as a default field value. Regardless, you can work around it by using a conversion factor: $area/10000. – csk Oct 10 '19 at 15:54

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.