ArcGIS Pro – Extracting Datasource of Feature Layer Selected in Tool Parameter for Validation Script

arcgis-proarcpytool-validation

I have a tool with a 'Feature Layer' input parameter where the user can select a feature layer from the TOC or a feature class by browsing. I would like to create an error message where the user is prompted if blanks are found in any non-nullable fields. I have the code working if a feature class is selected by browsing but I can't seem to work out how to determine the datasource if a layer is selected from the TOC.

def updateMessages(self):
# Customize messages for the parameters.
# This gets called after standard validation.
# Check for any non-nullable cells that don't have a value as the copy won't work if kept blank and flag an error to prompt the user to fix.
    if self.params[0].value:
        blank_cell_count = 0
        with arcpy.da.SearchCursor(self.params[0].value.value, [f.name for f in arcpy.ListFields(self.params[0].value.value) if f.isNullable is not True]) as cursor:
            for i, row in enumerate(cursor):
                blank_fields = [name for name, val in zip(cursor.fields, row) if val == ""]
                blank_cell_count += len(blank_fields)
                if blank_fields:
                    self.params[0].setErrorMessage("{0} no data cells found in the following non-nullable fields; {1}".format(blank_cell_count, ', '.join(blank_fields)))

Best Answer

Ok, I think I luckily managed to sort it. Code below:

def updateMessages(self):
# Customize messages for the parameters.
# This gets called after standard validation.
# Check for any non-nullable cells that don't have a value as the copy won't work if kept blank and flag an error to prompt the user to fix.
if self.params[0].value:
    blank_cell_count = 0
    if arcpy.Exists(self.params[0].value):
        param0 = self.params[0].value
    else:
        aprx = arcpy.mp.ArcGISProject("CURRENT")
        aprx_map = aprx.activeMap
        for lyr in aprx.ListLayers():
            if lyr.name == self.params[0].value.value:
                param0 = lyr.dataSource
    with arcpy.da.SearchCursor(param0, [f.name for f in arcpy.ListFields(param0) if f.isNullable is not True]) as cursor:
        for i, row in enumerate(cursor):
            blank_fields = [name for name, val in zip(cursor.fields, row) if val == ""]
            blank_cell_count += len(blank_fields)
            if blank_fields:
                self.params[0].setErrorMessage("{0} no data cells found in the following non-nullable fields; {1}".format(blank_cell_count, ', '.join(blank_fields)))
Related Question