I am trying to find a specific field name in layers in a current working MXD, but I'm having problems getting it right. The overall goal is to loop through layers in an MXD and set a definition query based on a user input (string type). The script runs without any errors, but no definition query is set.
Could it be because the type returned by the arcpy.Describe().fields function is Unicode?
Any help or advice is greatly appreciated!
import arcpy
#User input as 'String' type
feederID = arcpy.GetParameterAsText(0)
#Variables
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
#Set definition query to user set parameters
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
fields = arcpy.Describe(lyr).fields
for f in fields:
if f.Name == "FEEDERID":
lyr.definitionQuery = """FEEDERID = """ + "'" + str(feederID) + "'"
arcpy.RefreshActiveView()
Solved! Go to Solution.
Micah,
Thank you very much for the response, but now I'm getting a different error.
Could this be because the layers I'm trying to set a definition query for are in a feature dataset?
Hmmm. Can you post the script that yielded this error? It looks like the error was caused by the lyr variable not being a valid input to the describe function.
I actually figured out the issue. I believe it was because I had layers in the MXD with broken data sources.
Thank you!!
All,
I finally got the script to successfully run thanks to all the kind people in this community. Below is the final code.
Dan Patterson is there a way to mark several people's replies as the correct answer? This seems like it was a team effort since everyone contributed to the overall answer.
import arcpy
#Get input from user
feederID = arcpy.GetParameterAsText(0)
ischecked = arcpy.GetParameterAsText(1)
#Variables
mxd = arcpy.mapping.MapDocument("CURRENT")
field = "FEEDERID"
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.isFeatureLayer:
fields = arcpy.Describe(lyr).fields
for f in fields:
if f.Name == field:
delim = arcpy.AddFieldDelimiters(lyr,field)
lyr.definitionQuery = delim + "='" + feederID + "'"
#Clear definition query
if ischecked == 'true':
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.isFeatureLayer:
lyr.definitionQuery = ""
arcpy.RefreshActiveView()
No multiple correct... so your options are to