I want to make a date and time updated field as I edit an attribute field in this format yyyy-mm-dd 00:00:00 (= 2016-05-08 11:04:00) - my local date/time. The data is in a QGIS 2.14 shapefile and Vector lines as screenshot bellow.
When a feature as NULL in the 'name' field, I want to enter a name for the road and the 'mod' field must receive de modified date/time like '2016-05-08 15:16:00'.
I already tried some options and failed. I need help to start from beginning.
- I create a new field, date/time type, but stays with NULL value after I edited, in the "name" field, or the feature it self.
- I used too, the expression now(), but stays with NULL value after I edited.
Note: the date seen there, 2016-04-14 is the first value created with "Field Calculator".
I am using QGIS 2.14.
Answer
You can use the following code which connects the attributeValueChanged
event to a function we can define which inserts the results of the $now
expression. Highlight your layer and copy/paste the following into the Python Console:
layer = qgis.utils.iface.activeLayer()
def update():
field = layer.fieldNameIndex('mod')
e = QgsExpression( " $now " )
e.prepare( layer.pendingFields() )
for feat in layer.selectedFeatures():
feat[field] = e.evaluate( feat )
layer.updateFeature( feat )
layer.attributeValueChanged.connect(update)
Select the feature by clicking the row number (shown in the red box in the image) or from the map canvas and edit any attribute for that feature. The attribute in your mod
field should update:
Note: I used a string field instead of date in order to get the time, otherwise the date field only records YYYY-MM-DD.
No comments:
Post a Comment