4

I'm new to Python and I'm trying to create a script which adds fields to a feature class. The provided script is running well, but I want to create an additional parameter, which asks for the required field length of the fields to be created. The field length is only important if the field type "TEXT" is selected. The script should only take the additional parameter into account if the user selects "TEXT" under the field type. I think I need to put an if...else statement, but I don't know how do that.

    import arcpy
    # input data set (feature class, shapefile)
    inputFC = arcpy.GetParameterAsText(0)
    # list of field names
    inputString =arcpy.GetParameterAsText(1)
    fieldList =inputString.split(";")
    fieldType = arcpy.GetParameterAsText(2)

    for name in fieldList:
        arcpy.AddField_management(inputFC , name, fieldType)
        arcpy.AddMessage ("field created: " + name)

    arcpy.AddMessage ("Calculation complete")

enter image description here

3

What if user will add multiple fields of different type? How would you match the types of the fields and the fields names?

If you want to provide an easy to work with interface for adding fields, you are really looking for the FieldMappings data type in the script tool parameters.

enter image description here

Create a new parameter of Field Mappings and look how one can add fields. User provides all the information necessary to create one or more fields. In your source code, you extract the information you need about each field user supplied.

import arcpy

fields_to_add = arcpy.GetParameter(0) #of `Field Mappings` type
for field in [item.fields[0] for item in fields_to_add]:
    arcpy.AddMessage('{}'.format([field.name, field.aliasName, field.type, field.length]))
    #arcpy.AddField_management(pass your params here)

After user has supplied the information in the UI, the code would print:

[u'NewFieldName', u'NewFieldName', u'String', 50]
[u'NewFieldName1', u'NewFieldName1', u'String', 50]

If you still would like to keep your approach getting all information about the fields without using field mappings, you have some more options:

  1. Use the Python toolbox Value Table.
  2. Use the Record Set data type.
  3. Use Tool Validation to handle the business rules on field names, data types etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.