QGIS feature form : Force attribute to save as uppercase

The easiest way is to set up two NAME field (NAME_1 and NAME_2 for exemple). The first being directly fill by the user, the second set as "hidden" in the feature form and with a default value set to upper("NAME_1"), don't forget to check the "Apply default value on update" box.

This will give you a field with the country name in uppercase but you will also have an useless second field with the country name in mixed case...


In the end I found a simple solution. if someone is going to have the same problems, here is the solution:

QGis 3.X

Layer properties -> select the attribute (that you want to capitalize,or whatever) -> Defaults -> set default value to upper( "NAME") , check Apply default value on update -> apply

enter image description here


You could use python to check each time the attribute value is changed or added and convert it to uppercase if necessary. According to the PyQGIS API docs the attributeValueChanged signal is emitted whenever an attribute value change is done in the edit buffer. And the featureAdded signal is emitted when a new feature has been added to the layer.

You can use the Project Macros to connect a functions to the attributeValueChanged and featureAdded events each time the project is loaded. Here's some quick code I used to test that it works:

from qgis.core import QgsProject

lyrName = "test"
fldNum=5

def openProject():
    lyr=QgsProject.instance().mapLayersByName(lyrName)[0]
    lyr.attributeValueChanged.connect(ChkName)
    lyr.featureAdded.connect(ChkNew)
    pass

def saveProject():
    pass

def closeProject():
    pass


def ChkName(fid,idx,v):
    if (idx==fldNum):
        if(not v.isupper()):
            layers=QgsProject.instance().mapLayersByName(lyrName) 
            layer = layers[0]
            layer.changeAttributeValue(fid, fldNum, v.upper())
            layer.updateFeature(layer.getFeature(fid))

def ChkNew(fid):
    layers=QgsProject.instance().mapLayersByName(lyrName) 
    layer = layers[0]
    f = layer.getFeature(fid)
    v = f.attribute(fldNum)
    if(not v.isupper()):
        layer.changeAttributeValue(fid, fldNum, v.upper())
        layer.updateFeature(layer.getFeature(fid))

enter image description here

Replace the text in the Project Macros with the code above and change the value of lyrName to the name of your layer, and change the fldNum to the column number (starting from zero) of the "NAME" column.

I swear initially I saw the value changing to uppercase as soon as I tabbed out of the field, but now I don't see the changes until I close and reopen the feature form/attribute table.

Tags:

Qgis

Features