You are here:GeoTux»Geo-Blogs»Desktop GIS»AutoFields plugin for QGIS

Statistics

Invitados: 57
Usuarios registrados: 3094
Usuarios en línea:
-
Registrados hoy:
-

Register

RSS

Blogs and News:
Recibe las actualizaciones en Geo-Noticias y Geo-Blogs

Get them by e-mail
Recibir Geo-Noticias y Geo-Blogs por e-mail

¿What is this about?

Latest Geo-Tweets

Thursday, 18 August 2016 04:23

AutoFields plugin for QGIS

Written by  German Carrillo
Rate this item
(1 Vote)

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.

 

Intro

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:

 

enter image description here

Usage

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:

  1. Choose your river layer;

    enter image description here

  2. Choose (or create first, if it doesn’t exist yet) a length field, and;

    enter image description here

  3. Set a expression choosing from given options (in this case, Length) or opening the Custom Expression dialog.

    enter image description here

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.

enter image description here

 

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.

 

Examples

  • 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:

  1. You need to get a reference to the AutoFieldManager class, which allows you to create, overwrite, and remove AutoFields. For that, we suggest you to define the function getAutoFieldManager():

    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
    
  2. Use the function getAutoFieldsManager() to get a reference to AutoFieldManager.

    afm = getAutoFieldsManager()
    
  3. 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 QgsVectorLayer instance), 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' ) 
    
  4. You can now create features, change geometries, or change attributes (either via QGIS GUI or PyQGIS) and your AutoField will automatically update the field coordinate for 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 coordinate field now must have the value -74.4.

  5. You can overwrite an AutoField (to change its expression) in this way:

    autoFieldId = afm.overwriteAutoField( layer=myPointLayer, fieldName=u'coordinate', expression=u'$y' )
    
  6. 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 -> Measurements if 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.



Known issues

  • When adding new features, AutoFields are updated only when you save changes. Tools like Split are 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 Redo commands in any of its forms, i.e., keyboard shortcut (Ctrl+Shift+R by 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 OK to 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).
  • If Undo is 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).



Acknowledgements

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.



Donations

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.

 

Suggested donation amount:

 

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.


Last modified on Monday, 12 September 2016 17:14

comments  

 
+1 # Very useful module!Anton Biatov 2016-10-31 09:39
Hi, German!
Very useful module!
I wrote a small review module AutoFields, in Russian in my blog:
https://gis-naturalist.blogspot.com/2016/10/AutoFields.html
Reply | Reply with quote | Quote
 
 
+1 # Re:tuxman 2016-10-31 15:09
Hi Anton,

thanks a lot for the review! Glad you find the plugin useful.

I'll share your post in our Twitter account (@GeoTux2).

Regards,

Germán
Reply | Reply with quote | Quote
 
 
0 # Great plugingael 2016-12-13 14:15
Hi German,

Your plugin is very useful. Is it possible to change the path when AutoFields is disabled ?
Thank you for your answer !
Gael
Reply | Reply with quote | Quote
 
 
+1 # Re:tuxman 2016-12-13 19:56
Hi Gael,

great that you find it useful.

What do you mean by path? What kind of layers do you use?

Are you changing the location of your layers and would like AutoFields to recognize the new location?

Regards,

Germán
Reply | Reply with quote | Quote
 
 
0 # Regael 2016-12-14 09:36
Hi German,

Yes I've changed the location of my layers (shapefile) and I want to modify the new location.

I've created a project with many parameters in AutoFields.

I want to use this project in new arborescence with a relative path.

So it's the same layers with same fields but the name of a folder is different.

Regards,

Gael
Reply | Reply with quote | Quote
 
 
+1 # Re:tuxman 2016-12-14 14:33
Hi Gael,

that feature is not yet supported. Some German company was also interested in it, they even offer to sponsor it. I'm waiting for their decision.

Keep in mind that AutoFields are not tied to a particular QGIS project. The solution I envision is more related to add import/export functionality to the plugin.

If you're interested in funding such feature, let me know.

Regards,

Germán
Reply | Reply with quote | Quote
 
 
0 # How exchange the "list of AutoFields"Vincent 2016-12-15 12:41
Hello,

I've followed, with interest, your chat about your great plugin. However the right question is where and how are keep the AutoFields setting in the computer ? Maybe, we could exchange a setting file and put it in the rignt place in each computer...

Thank you and have a nice day,

Vincent
Reply | Reply with quote | Quote
 
 
+1 # Re:tuxman 2016-12-15 15:18
Hi,

AutoFields definitions are stored by Qt in the operating system as key-value pairs. On GNU/Linux, AutoFields are in /home/user/.config/QGIS, whereas on Windows, AutoFields are stored in the registry.

In that way, AutoFields can persist across QGIS sessions and be independent of QGIS projects.

I would not recommend users change those settings by hand, and that's why import/export functionality may be handy.

Regards,

Germán
Reply | Reply with quote | Quote
 

Add comment


Security code
Refresh

 

On-line users

Latest Geo-Forums

More Topics »

Latest Comments