This is based on a previous question/answer that I had. Replacing values in multiple columns using QGIS Field Calculator?
I need it to update 3 fields now and I get an name 'e' is not defined error. What have I done wrong?
layer = qgis.utils.iface.activeLayer()
# Set field names you want to update
field_1 = "New_Name"
field_2 = "New_File_P"
field_3 = "Process"
idx_1 = layer.fieldNameIndex( field_1 )
idx_2 = layer.fieldNameIndex( field_2 )
idx_3 = layer.fieldNameIndex( field_3 )
# Set expression to find all features which fall into expression
exp = QgsExpression( """ "Existing_F" LIKE '%2015 Aerial Ortho\\_2015\\ECW_Tiles%' """ )
# Select all features which fall into expression
ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(exp))]
layer.setSelectedFeatures(ids)
# Set expressions to fill in values for selected features
formula_1 = """ "File_Name" """
formula_2 = """ '\\sipv-gis01\\GIS_Library\\Raster\\Aerial\\2015_25cm\\Images\\ECW' """
formula_3 = """ 'y' """
e_1 = QgsExpression(formula_1)
e_2 = QgsExpression(formula_2)
e_3 = QgsExpression(formula_3)
e.prepare(layer.pendingFields())
with edit(layer):
# For each selected feature
for f in layer.selectedFeatures():
f[idx_1] = e_1.evaluate(f)
f[idx_2] = e_2.evaluate(f)
f[idx_3] = e_3.evaluate(f)
layer.updateFeature(f)
Error
e.prepare(layer.pendingFields())
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'e' is not defined
==== I needed to do this again and here's the QGIS 3x code =====
#search and replace text in all fields of all layers in map
#set text to search for and replace with.
#CAUTION Partial match is allowed
#Based on https://gis.stackexchange.com/questions/317855/search-and-replace-text-in-all-fields-in-qgis-3
searchText = "Bougainvilia"
replaceText = "Bougainvillea"
#run on active layer
#layer = iface.activeLayer()
#run on all layers
layers = QgsProject.instance().mapLayers()
i=1
for layer_id, layer in layers.items():
print("Layer: %s" % (layer.name()))
# get data provider
dpr = layer.dataProvider()
for field in layer.fields():
fieldName=field.name()
for feature in layer.getFeatures():
inText = str(feature[fieldName])
# get field index
fieldIndex = layer.fields().indexFromName(fieldName)
#print ("Checking %s" % (inText))
if searchText in inText:
# change inText
print ("%s . REPLACED: %s in %s with %s in column: %s" % (i, searchText, inText, replaceText, fieldName))
outText = inText.replace(searchText, replaceText)
i+=1
# save changes
dpr.changeAttributeValues({feature.id(): {fieldIndex: outText}})
print ("Completed")
exp
QgsExpression you declared in line ~20?e.prepare(layer.pendingFields())
.exp = QgsExpression( """ "File_Type" = 'shp' """ )
. Don't think I can help much further, sorry -_-