Find Specific Field Name in MXD Layers

2390
14
Jump to solution
09-29-2016 11:39 AM
MitchHolley1
MVP Regular Contributor

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()
Tags (2)
0 Kudos
14 Replies
MitchHolley1
MVP Regular Contributor

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?

0 Kudos
MicahBabinski
Occasional Contributor III

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.

MitchHolley1
MVP Regular Contributor

I actually figured out the issue.  I believe it was because I had layers in the MXD with broken data sources. 

Thank you!!

MitchHolley1
MVP Regular Contributor

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()
DanPatterson_Retired
MVP Emeritus

No multiple correct... so your options are to

  • 'Helpful' all those that contributed
  • pick one as the most helpful either singularly, or cumulatively
  • mark it as 'assumed answered' if you can't pick one