AnsweredAssumed Answered

Toggling Fields within a Feature Class On and Off

Question asked by vshah6 on Jul 12, 2017
Latest reply on Jul 13, 2017 by vshah6

So I've been doing some research into this but have gotten conflicting outputs on whether or not it is possible to turn fields on and off using python in custom tools. I am working on a custom tool that generates KMZs on a state by state level for different departments within the company, but we do not let them see all the attributes within each feature class, thus turning some fields off before we use Map to KML tool. Since I am currently trying to automate this process, I want the custom tool to first turn the fields I do not want shown in the report off before the tool gets to the actual execution in regards to generating the KMZs. One such discussion I looked at was this on titled Turn fields off by script. While Wayne's solution seemed to work for the OP, there were parts of that solution I did not understand. Is there an easier way to approach this or if someone can help break down Wayne's solution, that would be appreciated. I look forward to seeing the ideas everyone has for this. 


For reference, here's what the solution to the other discussion:


import arcpy
from arcpy import env
arcpy.env.overwriteOutput = True
arcpy.env.addOutputsToMap = False
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, '*')[0]
LayerNeedsFieldsTurnedOff = arcpy.mapping.ListLayers(mxd, 'your target layer name', df)[0]
# fill in your desired fields to remain visible
desiredFields = ['fieldname0', 'fieldname1', 'fieldname2', 'etc']
field_info = arcpy.Describe(LayerNeedsFieldsTurnedOff).fieldInfo
for i in range(field_info.count):
    if field_info.getfieldname(i) not in desiredFields:
        field_info.setvisible(i, 'HIDDEN')
arcpy.MakeFeatureLayer_management(LayerNeedsFieldsTurnedOff, 'temp_layer', '', '', field_info)
refLyr = arcpy.mapping.Layer('temp_layer')
# rename the ref layer the same as your target layer = 'your target layer name' 
arcpy.ApplySymbologyFromLayer_management(refLyr, LayerNeedsFieldsTurnedOff)
arcpy.mapping.UpdateLayer(df, LayerNeedsFieldsTurnedOff, refLyr, False) 
print 'cleaning up-'
if arcpy.Exists('temp_layer'):
    print '\'temp_layer\' still in memory...deleting now...'
print 'deleting obj refs...'
del mxd,LayerNeedsFieldsTurnedOff, refLyr print 'done.'