This plugin allows you to configure vector fields to be automatically calculated for you when digitizing new features or modifying existing ones. Think about them as triggers in a database or as an automatic Field Calculator.
A very common requirement for GIS people is to get automatic attribute values when creating or modifying vector features. Think about digitizing features of a point layer and getting X and Y coordinate values automatically.
While this is a common scenario when working with vector layers, usually GIS tools don’t provide us with an easy way to achieve it. Some vector formats (or the software behind them) allow GIS experts to set triggers, which are custom actions that occur after creating, modifying, or removing table records. PostgreSQL/PostGIS and SQLite/SpatiaLite support triggers, but despite their powerful capabilities, trigger creation is not what all GIS users would like to deal with, and is often assigned to DB managers.
The AutoFields plugin for QGIS allows GIS users to set automatic calculations when creating or modifying vector features. You can install it from the official QGIS plugin repository and open its main window doing click on a button that looks like this:
An AutoField can be created choosing a vector layer, a field (or column), and an expression (or value).
For example, if you want to automatically get the length of the rivers you are about to digitize:
- Choose your river layer;
- Choose (or create first, if it doesn’t exist yet) a length field, and;
- Set a expression choosing from given options (in this case,
Length) or opening the Custom Expression dialog.
Once you’ve saved the AutoField, any time you create a new line, modify an existing geometry (line), or modify any attribute of a river on your river layer, its corresponding length field’s value will be updated to the calculated length.
AutoFields will be remembered by QGIS for you. You can even close QGIS. Next time you load the same layer, AutoFields will be enabled and ready to help you keep values up-to-date.
If you want to remove some AutoFields, go to tab
List of AutoFields, select AutoFields to remove and click on
Remove AutoFields. Note that the created field (length) won’t be removed, only its associated AutoField.
If you don’t want to remove an AutoField, but overwrite (or edit) its expression, you can repeat steps 1 to 3. Once you click on
Save AutoFields, the plugin will recognize you’re attempting to write over an existing AutoField and you’ll be asked whether you want to overwrite it.
You can have a look at the following examples, which show you how to set AutoFields to solve common use cases in the GIS realm. Don’t forget to enable subtitles, they are available in English and Spanish.
- Auto-populate geometric properties and keep them up-to-date (e.g., start and end coordinates of lines).
- Set automatic IDs for a Shapefile.
- Get a time stamp when a feature is digitized or edited.
- Automatically calculate area and population density (an AutoField depending on another AutoField).
- Auto-populate elevation (from a DEM) for points using a Python function as expression.
Using AutoFields from PyQGIS
You can create, overwrite, and remove AutoFields from other QGIS plugins, from the QGIS Python Console, or from a standalone PyQGIS script. Have a look at the following steps:
- You need to get a reference to the
AutoFieldManagerclass, which allows you to create, overwrite, and remove AutoFields. For that, we suggest you to define the function
from qgis import utils def getAutoFieldsManager(): if not utils.isPluginLoaded('AutoFields'): if 'AutoFields' in utils.available_plugins: utils.loadPlugin('AutoFields') utils.startPlugin('AutoFields') af = utils.plugins['AutoFields'] return af.autoFieldManager else: print "It seems AutoFields plugin is not installed. Could you please check it?" return None
- Use the function
getAutoFieldsManager()to get a reference to
afm = getAutoFieldsManager()
- This is how you create AutoFields using PyQGIS. In the next example, you’ll be creating an AutoField on layer
myPointLayer(which must be a
QgsVectorLayerinstance), on its field
coordinate(field should exist in
myPointLayer), with the expression
$x, which will give you the X coordinate.
if afm: autoFieldId = afm.createAutoField( layer=myPointLayer, fieldName=u'coordinate', expression=u'$x' )
- You can now create features, change geometries, or change attributes (either via QGIS GUI or PyQGIS) and your AutoField will automatically update the field
coordinatefor you! Just keep in mind that, if using PyQGIS, you need to perform the edits within an edit session and not directly to the data provider. For example:
tmpFeature = QgsFeature( myPointLayer.pendingFields() ) tmpFeature.setGeometry( QgsGeometry.fromPoint( QgsPoint(-74.4, 4.5) ) ) myPointLayer.startEditing() myPointLayer.addFeature( tmpFeature ) myPointLayer.commitChanges()
Your new feature’s
coordinatefield now must have the value
- You can overwrite an AutoField (to change its expression) in this way:
autoFieldId = afm.overwriteAutoField( layer=myPointLayer, fieldName=u'coordinate', expression=u'$y' )
- Finally, you can remove the AutoField created some steps before, running this:
afm.removeAutoField( autoFieldId )
If you want to use AutoFields without GUI, for example, in a standalone PyQGIS script, you can have a look at the tests of the plugin (Tests.py). Should you have any question about it, just post a comment in this blog post.
Frequently Asked Questions (FAQ)
- On which QGIS versions does AutoFields plugin work?
You can use AutoFields on QGIS v2.12.x or greater. Although you need v2.14.x if you want to get geometric properties (e.g., area, length, and perimeter) converted from layer CRS (Coordinate Reference System) units to units defined in the QGIS project.
- ¿Does the AutoField plugin update all my layer features (table rows)?
Yes! From version 0.4.0 on, when creating an AutoField, you can choose if you want to calculate the expression on existing features of your layer. This ensures that all the layer features (those that already exist and those that you create from there on) will always have the field calculated and up-to-date.
- Do AutoFields work with ‘X’ vector format?
We’ve already tested AutoFields on PostgreSQL/PostGIS, SpatiaLite, Shapefiles, WFS-T (Transactional Web Feature Service) and Memory layers. Please let me know if you use AutoFields on other vector formats.
- Are AutoFields like Virtual Fields?
Nope. Unlike Virtual Fields, AutoFields:
- Store calculated values in the data;
- Are independent of QGIS projects, i.e., you can switch between QGIS projects and AutoFields will still work;
- Only work on editable vector layers.
- Can I create multiple AutoFields per layer?
Yes, you can.
- How are AutoFields linked to my layer?
The AutoFields you create for a layer are linked to layer source (e.g., the path for a Shapefile or a connection string for a PostGIS layer). That means that if you change the directory of a Shapefile or the schema name of your PostGIS layer, AutoFields won’t be able to find their associated layer and will be disabled.
- Can I get geometry properties such area, length, and perimeter in other units?
Distance and area calculations take units defined in the project into account. Go to
Project -> Project properties -> General -> Measurementsif you want to set other units for calculations.
- Can I use AutoFields on memory layers?
By and large, you can use AutoFields on memory layers smoothly, as long as you don’t want to use them across QGIS sessions. In fact, memory layers are not intended to work across QGIS sessions, since their features are deleted when closing QGIS.
- What happens if a user adds the same layer twice?
Existing AutoFields will be set only to the first layer loaded and not to the duplicated one. As a recommendation, if you have to load duplicated layers, stick to one of them (the one that was loaded first) to configure (add, overwrite, remove) AutoFields and make edits. If you start creating AutoFields on several duplicated layers, results might become unpredictable.
- Can I create multiple AutoFields at the same time?
Yes, you can. For example, if you want to get X coordinate updated on several point layers, select all of them in the Layers list, set a New Field (you could even select a common existing field if selected layers have fields in common), and choose X Coordinate from the Value or Expression section. Finally, click on Save AutoField.
- How can I temporarily disable an AutoField to perform other edits?
Add a duplicated layer and make edits on it, these edits will be propagated to the original layer without triggering actions for AutoFields.
- Can I edit an AutoField value manually?
You can edit attributes whose field is an AutoField, manually or even using the Field Calculator on them, however, you must keep in mind that as soon as the corresponding feature is edited, the value you edited manually in the AutoField will be overwritten.
- What if I have to update thousands of features at once?
For batch updates we recommend you to use the Field Calculator. It’s way faster as it’s optimized for such labor. AutoFields give you the possibility of automating calculations and is intended to work on single or small groups of features.
- When adding new features, AutoFields are updated only when you save changes. Tools like
Splitare also affected by this issue, since when you split an object, at least one of the resulting parts is added as new feature. (This is to avoid a crash due to QGIS issue #15311)
- You’d better not use
Redocommands in any of its forms, i.e., keyboard shortcut (
Ctrl+Shift+Rby default), buttons, or from PyQGIS. QGIS will crash sooner or later! (QGIS issue #15311)
- When editing with forms, the form doesn’t show the automatic value, but you just need to click in
OKto see the automatic value in the attribute table.
- Writing directly to data provider (e.g., via PyQGIS) has no SIGNAL, so it’s not possible to keep track of such edits (see thread in QGIS-dev mailing list).
- Sometimes, starting an edit session from the attribute table with NULL values emits attributeValueChanged SIGNAL several times (see thread in QGIS-dev mailing list).
Undois used and the edit session is closed without saving changes, the AutoFields will retain values. If, for instance, they were NULL before start editing, once the edit session is closed they won’t be NULL but will retain some value from calculations. (Related to QGIS issue #15311)
- Adding New Fields to PostGIS layers doesn’t work (QGIS issue #13743).
Special thanks to all testers who volunteered: Thomas Baumann, Hennessy Becerra, Miguel Ángel Blanco, Diego Cordero, Erwin Galvis, Romina González Musso, Andrés Guarín, William Guerrero, Arturo Lorenzo, Sandra Liliana Moreno, Enrique Morón, Leonardo Porto Nazareth, and Marcela Suárez. They all provided me with useful comments and suggestions making AutoFields much better for you.
Thanks to all QGIS devs, they do the hard work to make this kind of development possible.
I wasn’t hired for developing this plugin. I developed it to fulfill a community need. So, if you (the community) would like to acknowledge this work, please donate so that I can get the money deserved. Besides the development itself, I’ll use your donations to maintain the plugin, to keep documentation up-to-date, to look into QGIS issues found and attempt to fix them, as well as to migrate AutoFields to the upcoming QGIS v3.x.
If you want to contribute in other ways (code, translations, reporting issues), please do it through the AutoFields GitHub repo.
Hope you find AutoFields useful!
You can contact me if you would like to hire me for developing a QGIS plugin you need.