#Introduction and imports
import arcpy, string
from arcpy import env
#User Inputs: layer, field name, output workspace (optional)
strTargetLayer = arcpy.GetParameterAsText(0)
strFieldName = arcpy.GetParameterAsText(1)
strSuffix = arcpy.GetParameterAsText(2)
strOutputWorkspace = arcpy.GetParameterAsText(3)
TargetLayer = arcpy.mp.Layer(strTargetLayer)
TargetLayerDQ = TargetLayer.definitionQuery
Field = arcpy.ListFields(strTargetLayer, strFieldName)[0]
env.workspace = strOutputWorkspace
env.overwriteOutput = True
mxd = arcpy.mp.ArcGISProject("CURRENT")
df = df.listMaps("Drill Plan Map-Main")[0]
cursor = arcpy.SearchCursor(strTargetLayer)
lstValues = []
#Creating set(lstValues)
for row in cursor:
lstValues.append(row.getValue(strFieldName))
lstValueSet = sorted(set(lstValues), reverse = True)
del lstValues
#Creating layers in map
arcpy.AddMessage("Creating layers in map...")
LyrList = []
for i in lstValueSet:
try:
if TargetLayerDQ !="":
if i is None:
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, "NULL" + strSuffix).getOutput(0)
ilyr.definitionQuery = TargetLayerDQ + ' and ' + "\""+Field.name+"\"" +' is NULL'
elif Field.type == 'String':
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, i + strSuffix).getOutput(0)
ilyr.definitionQuery = TargetLayerDQ + ' and ' + "\""+Field.name+"\"" +' = ' + "\'"+ i +"\'"
else:
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, str(i) + strSuffix).getOutput(0)
ilyr.definitionQuery = TargetLayerDQ + ' and ' + "\""+Field.name+"\"" +' = ' + str(i)
arcpy.mapping.InsertLayer(df,TargetLayer,ilyr,"AFTER")
else:
if i is None:
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, "NULL" + strSuffix).getOutput(0)
ilyr.definitionQuery = "\""+Field.name+"\"" +' is NULL'
elif Field.type == 'String':
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, i + strSuffix).getOutput(0)
ilyr.definitionQuery = "\""+Field.name+"\"" +' = ' + "\'"+ i +"\'"
else:
ilyr = arcpy.MakeFeatureLayer_management(TargetLayer, str(i) + strSuffix).getOutput(0)
ilyr.definitionQuery = "\""+Field.name+"\"" +' = ' + str(i)
arcpy.mapping.InsertLayer(df,TargetLayer,ilyr,"AFTER")
LyrList.append(ilyr.name)
except:
if arcpy.GetMessages(2) != "":
arcpy.AddMessage("**FAILED TO EXECUTE FOR " + str(i) + "**")
arcpy.AddMessage(arcpy.GetMessages(2))
pass
#Saving layers to folder
if strOutputWorkspace != "":
arcpy.AddMessage("Saving layers in target location...")
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.name in LyrList:
arcpy.SaveToLayerFile_management(lyr.name,lyr.name,"ABSOLUTE")