2

I want to update my date field to the current date when a checkbox has been checked.The date field is Sur_com, the checkbox is Sur_check.

I have tried codes below:

First:

layer = qgis.utils.iface.activeLayer()

f1 = 'Sur_com'
f2 = 'Sur_check'

def updateDATE(f1,f2):
e = QgsExpression("$now")
for feat in layer():
if f2 is True:
feat[f1] = e.evaluate()
layer.updateFeature(feat)

Second:

layer = qgis.utils.iface.activeLayer()

f1 = 'Sur_com'
f2 = 'Sur_check'
e = QgsExpression("$now")

if f2 is True:
f1 = e.evaluate()
layer.updateFeature()

Although those codes don't give any error and are executed in the python console, the date field still needs to click to appear today's date.

Is it my code that has a problem?

Lilium
  • 1,057
  • 1
  • 6
  • 17
LEI
  • 65
  • 5

1 Answers1

6

You need to refresh the Attribute Table. Today's day appears after you click, because the Attribute Table is refreshed when you click.

Add this code to the last line.

QgsProject.instance().reloadAllLayers()

Or use the following script:

layer = iface.activeLayer()

f1 = 'Sur_com' f2 = 'Sur_check' e = QgsExpression("$now")

layer.startEditing()

for feat in layer.getFeatures(): if feat[f2] is True: feat[f1] = e.evaluate() layer.updateFeature(feat)

layer.commitChanges()

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
  • Hi Kadir, Thank you for response, but which code should I use and how should I put this last line in? I have tried both and put your code after an empty row with no space before it. But it's not working – LEI Mar 23 '22 at 10:54
  • Hi Kadir, I have tried your code, but it still needs to click on the date box to populate the date. Can it be done by just checking the checkbox? – LEI Mar 23 '22 at 13:08
  • I don't know. It works on my computer. – Kadir Şahbaz Mar 23 '22 at 13:21