I'm developing a script tool that allows users to select specific features on a map. The tool has three parameters:
Layer – The user selects the target map layer.
Layer Field – The user chooses a field within the selected layer.
Layer Field Attribute – The user selects an attribute value within the chosen field.
Once all parameters are set, the user runs the tool. However, despite receiving no errors, nothing gets selected on the map.
Script
import arcpy
class ToolValidator:
def __init__(self):
self.params = None
def initializeParameters(self):
return
def updateParameters(self):
# If the layer is selected, and it is a feature layer
if self.params[0].value:
layer_name = self.params[0].valueAsText
try:
fields = [f.name for f in arcpy.ListFields(layer_name)]
if "PLAT_NAME" in fields:
self.params[1].value = "PLAT_NAME" # Auto-populate the field name
# Get unique values from the PLAT_NAME field
values = set()
with arcpy.da.SearchCursor(layer_name, ["PLAT_NAME"]) as cursor:
for row in cursor:
if row[0]:
values.add(row[0])
self.params[2].filter.list = sorted(values)
else:
self.params[1].value = None
self.params[2].filter.list = []
except Exception as e:
self.params[1].value = None
self.params[2].filter.list = []
return
def updateMessages(self):
return
def main():
# Parameters
layer_name = arcpy.GetParameterAsText(0) # Layer name to select from map
field_name = arcpy.GetParameterAsText(1) # Field to search (e.g., PLAT_NAME)
acc_val = arcpy.GetParameterAsText(2) # Attribute value (e.g., "BRIDGEWATER ESTATES #3")
if not layer_name or not field_name or not acc_val:
arcpy.AddError("Layer, field name, or search value is missing.")
return
# Access current project, map, and layout
project = arcpy.mp.ArcGISProject("CURRENT")
active_map = project.listMaps()[0]
layout = project.listLayouts()[0] # Layout is not used here, but included if needed
# Get the target layer by name
try:
target_layer = active_map.listLayers(layer_name)[0]
except IndexError:
arcpy.AddError(f"Layer '{layer_name}' not found in the map.")
return
# Build where clause using input values directly (no escaping)
expression = "{0} = '{1}'".format(field_name, acc_val)
where_clause = str(expression)
arcpy.AddMessage(f"Where clause: {where_clause}")
# Perform the selection
arcpy.management.SelectLayerByAttribute(target_layer, "NEW_SELECTION", where_clause)
# Count and report results
count = int(arcpy.management.GetCount(target_layer)[0])
if count == 0:
arcpy.AddWarning(f"No features found where {field_name} = '{acc_val}'.")
else:
arcpy.AddMessage(f"Selected {count} feature(s) where {field_name} = '{acc_val}'.")