Saturday 15 April 2017

Detecting Join programmatically using ArcPy?


I have some Python code that is launched from within an ArcMap project. Any joins that the user may have created in the project must be removed in order for my code to run. Unfortunately, the code that removes a join… arcpy.RemoveJoin_management("layer1", "layer2")… also breaks some of the layer properties that are critical to my application (highlighted fields, read-only fields, etc).


If joins are removed by right-clicking the layer in ArcMap and choosing “Remove Joins” the layer properties are left intact.



If I can detect that a join exists from within my code, I will simply exit the code and display a message that the user must manually remove their joins before attempting to run the code. So… Can a Join be detected programmatically?



Answer



Too bad there's not a hasJoin property on the arcpy.Layer class. I think you can test for a join by looking at field names though. Here's a simple proof of concept for data in a file geodatabase:


import arcpy, arcpy.mapping as arc

def joinCheck(lyr):
fList = arcpy.Describe(lyr).fields
for f in fList:
if f.name.find(lyr.datasetName) > -1:
return True

return False

arcpy.env.workspace = r''
mxd = arc.MapDocument(r'')
lyrs = arc.ListLayers(mxd)
for lyr in lyrs:
# ignore group layers
if not lyr.isGroupLayer:
hasJoin = joinCheck(lyr)
if hasJoin:

print '\nFound a join: %s.' % lyr.datasetName
else:
print '\nNo join found on %s.' % lyr.datasetName

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...