I am trying to add a feature layer to my map document as the output from my python script. The goal is to limit the number of fields in the attribute table to a pre-defined list. I am able to add the feature layer to my map document, but all of the fields display. However, when I use arcpy.Describe() on the layer my script added to the map, the Describe results show the desired field subset. I can't figure out what is going on.
def makeFeatureLayer(outputFC, fieldTable, input_FC, input_ID, mapLayers):
outputFeatureLayer = "{0}".format(os.path.basename(outputFC))
subField = "{0}".format(arcpy.Describe(outputFC).subtypeFieldName)
displayFieldList = [input_ID, subField]
with arcpy.da.SearchCursor(fieldTable, ["layer_name", "Attribute"]) as cursor:
for row in cursor:
if "{0}".format(row[0]) == "{0}".format(os.path.basename(input_FC)):
displayFieldList.append("{0}".format(row[1]))
outputFieldList = arcpy.ListFields(outputFC)
fieldInfo = "{0}".format(input_ID) + " " + "{0}".format(input_ID) + " " + "VISIBLE" + " " + "NONE;" + "{0}".format(subField) + " " + "{0}".format(subField) + " " + "VISIBLE" + " " + "NONE;"
for f in outputFieldList:
if f.name in displayFieldList:
fieldInfo = fieldInfo + f.name + " " + f.name + " " + "VISIBLE" + " " + "NONE;"
else:
fieldInfo = fieldInfo + f.name + " " + f.name + " " + "HIDDEN" + " " + "NONE;"
arcpy.management.MakeFeatureLayer(outputFC, outputFeatureLayer, "", "", fieldInfo)
mapLayers.append(outputFeatureLayer)
del subField, displayFieldList, outputFieldList, fieldInfo
def updateMap(mapLayers):
mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd)[0]
for layer in mapLayers:
arcpy.mapping.AddLayer(dataFrame, arcpy.mapping.Layer(layer), "TOP")
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, dataFrame
I tried leaving out arcpy.mapping.Layer in case this was undoing the fieldInfo settings/field selection, and just trying to add the feature layer to the map document directly, but that generates an assertion error. Also, if I run the code it actually results in two new layers to my map document: a visible layer that shows all the fields, and the original output of the MakeFeatureLayer tool, but it is not visible and cannot be added to the map display unless I export it to a .lyr file first.
Any ideas?
I was able to get MakeFeatureLayer to work from the Python window just fine. I tried to use ListLayers() and use that to get at the feature layer after creating it, but that didn't work either.
I can sort of work around this by saving the results of MakeFeatureLayer to a .lyr file, but this is not ideal as I do not want to write anything extra to disk just for the field display. When I add the .lyr file to the map document, though, it works the way I intend and only shows the subset of fields.