I created a simple tool that renames layers in the TOC using a for
loop. As a tool within my normal toolbox it works fine. Now I´m trying to work more and more with the Python Toolbox and want to migrate the script there. It has these two parameters:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Rename layers in TOC"
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = arcpy.Parameter(
name="in_string",
displayName="String to be replaced",
datatype="GPString",
parameterType="Required",
direction="Input")
param1 = arcpy.Parameter(
name="out_string",
displayName="will be replaced by",
datatype="GPString",
parameterType="Required",
direction="Input")
params = [param0,
param1,
param2]
return params
...
def execute(self, parameters, messages):
"""The source code of the tool."""
in_string = parameters[0].valueAsText
out_string = parameters[1].valueAsText
mxd = arcpy.mapping.MapDocument("CURRENT")
layers = arcpy.mapping.ListLayers(mxd)
for layer in layers:
if in_string in layer.name:
layer.name = layer.name.replace(in_string, out_string)
It goes through layer names in TOC and if in_string is found, it will be replaced by out_string. My problem is that if it founds a layer that matches the criteria, ArcMap probably renames it but immediately after that it removes the layer from the TOC.
As I was searching through the documentation and similar questions and answers here I found out that it treats that layer as a temporary one (that´s why it gets deleted from TOC) and a derived output must be set. That´s the point where I´m getting lost.
If I create a new parameter:
param2 = arcpy.Parameter(
name="somelayer",
displayName="somelayer",
datatype="GPFeatureLayer",
parameterType="Derived",
direction="Output")
param2.parameterDependencies = [????]
param2.schema.clone = True
... I don´t think there is a suitable parameter for parameterDependecies
because param0 and param1 are both strings. I need somehow to set the derived parameter to the layer that is being currently evaluated (for layer in layers...
), is it possible to set the layer as derived while looping?
Where should I put a derived parameter? Or is there another way how I can make the layers in the TOC permament? Or could you give me some example (or maybe the solution) how to make it work? Neither the ArcGIS documentation nor another threads are quite clear for me.