Select to view content in your preferred language

How to add layer to TOC after using MakeFeatureLayer (management)

3674
11
Jump to solution
07-13-2017 06:08 AM
VishalShah2
Occasional Contributor II

So I'm working on a custom tool that generates KMZs for reports to go out ot various different departments. One thing that we do is turn certain fields off not to show every attribute in the table. Thus, I settled on using MakeFeatureLayer_management tool to create a new feature layer with only the fields I want shown in the report. Here is what my code looks like:

visibleFields = ["Field1", "Field2", "Field3", "Field4", "Field4"]
field_info = arcpy.Describe('Input Feature Layer').fieldInfo

for index in xrange(0, field_info.count):
    if field_info.getfieldname(index) not in visibleFields:
        field_info.setvisible(index,"HIDDEN")
arcpy.MakeFeatureLayer_management('Input Feature Layer','Output Feature Layer',"","",field_info)
arcpy.RefreshTOC()
arcpy.RefreshActiveView()‍‍‍‍‍‍‍‍‍

When I run this in the python module in ArcMap, the output feature layer is automatically added to the Table of Contents. But when I run this in my custom tool, the output feature layer isn't added to the Table of Contents and my custom tool spits out an error because the tool cannot progress as the output feature layer does not exist in the Table of Contents and cannot be referred on. So how would I be able to add the newly created feature layer to the table of contents in the script when the feature layer is created in program memory?

0 Kudos
11 Replies
JoshuaBixby
MVP Esteemed Contributor

You are correct, AddLayer expects a data frame object, not the name of a data frame.  You were passing a string to the function instead of a data frame object, hence the assertion error.

VishalShah2
Occasional Contributor II

As always, thank you Joshua! Your help and input has been greatly appreciated and very helpful.

0 Kudos