Thursday, 17 November 2016

arcpy - Setting up Drop-Down list in Parameters of Python script tool?


I am trying to create a tool from a python script I have written that will take a list I have created and use it as a drop-down menu in the finished tool as one of the inputs (see attached image for example):



enter image description here


The list I am using is a large list that includes all the towns in the state of Vermont, and I generate it in the script from a table (see code below). I suspect my problem at the moment is just with setting the tool Properties to take this list and use it to create a drop-down list for the user. Here is the block of code that creates the list for use in the parameter - does anybody see any problems with this code-end of the tool?


import arcpy
arcpy.env.workspace = "Z:\\OPS\\TechnicalServices\\Culverts\\GetCulverts\\GetCulverts.gdb"
towns = "Database Connections\\GDB_GEN.sde\\GDB_Gen.VTRANS_ADMIN.townindex"
arcpy.MakeFeatureLayer_management(towns,"towns_lyr")

NameList = []
NameListArray = set()
rows = arcpy.SearchCursor("towns_lyr")

for row in rows:
value = row.getValue("TOWNNAME")
if value not in NameListArray:
NameList.append(value)
town = NameList

town = arcpy.GetParameterAsText(0)

Here is an image of the Tool properties as well, with the default validation code - do I need to alter this validation code?


I looked for info on altering this validation code, but I could not find info on using it for formatting drop-down lists.



enter image description here



Answer



Try setting the tool validator class code to this:


import arcpy
class ToolValidator(object):
"""Class for validating a tool's parameter values and controlling
the behavior of the tool's dialog."""

def __init__(self):
"""Setup arcpy and the list of tool parameters."""

self.params = arcpy.GetParameterInfo()

def initializeParameters(self):
"""Refine the properties of a tool's parameters. This method is
called when the tool is opened."""
return

def updateParameters(self):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter

has been changed."""
towns = "Database Connections\\GDB_GEN.sde\\GDB_Gen.VTRANS_ADMIN.townindex"
rows = arcpy.SearchCursor(towns)
self.params[0].filter.list = sorted(list(set(r.getValue('TOWNNAME') for r in rows)))
del rows
return

def updateMessages(self):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""

return

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...