handleAutoFill method

void handleAutoFill(
  1. Field field
)

Implementation

void handleAutoFill(Field field) {
  if (field.autoFill == null || autoFillInProgress[field.name] == true) {
    return;
  }

  autoFillInProgress[field.name] = true;

  for (final autoFill in field.autoFill!) {
    final condition = autoFill.condition;
    bool conditionMet = true;

    if (condition != null) {
      final value = values[condition.field];
      conditionMet = condition.values.contains(value);
    }

    if (conditionMet) {
      for (final mapping in autoFill.mappings) {
        final targetField = mapping.targetField;
        dynamic sourceValue;

        switch (mapping.type) {
          case 'option':
            final selectedOption = options[field.name]?.firstWhere(
              (opt) => opt.value.toString() == values[field.name]?.toString(),
              orElse: () => Option(label: "", value: null),
            );
            if (selectedOption?.value != null &&
                selectedOption?.item != null) {
              sourceValue = selectedOption?.item![mapping.sourceField!];
            }
            break;

          case 'constant':
            sourceValue = mapping.sourceValue;
            break;

          case 'value':
            sourceValue = values[mapping.sourceField!] ?? "";
            break;

          default:
            debugPrint("Unknown mapping type: ${mapping.type}");
        }

        // Optional: convert to target data type
        if (sourceValue != null) {
          sourceValue = convertDataType(mapping.dataType, sourceValue);
        }

        if (sourceValue != null && values[targetField] != sourceValue) {
          values[targetField] = sourceValue;
        }
      }
    }
  }

  autoFillInProgress[field.name] = false;
  notifyListeners();
}