handleRemoveMore method

void handleRemoveMore(
  1. String componentName,
  2. int indexToRemove
)

Implementation

void handleRemoveMore(String componentName, int indexToRemove) {
  var formDefinition = formDefinitions[componentName];
  if (formDefinition == null) return;

  // Prevent deletion if first index is mandatory
  if (indexToRemove == 0 && (formDefinition.mandatoryFirstIndex ?? false)) {
    return;
  }

  // Decrement startWithIndex
  formDefinition.startWithIndex = (formDefinition.startWithIndex ?? 0) - 1;

  // Get all fields for the section to be deleted
  final fieldsToDelete = extractFields(formDefinition, index: indexToRemove);
  if (fieldsToDelete.isEmpty) return;

  // Get base path pattern (e.g., 'existing_loans')
  final basePathPattern = fieldsToDelete.first.name.split('[').first;

  // Helper: does a field belong to the section being deleted?
  bool isFieldInTargetSection(String fieldName) {
    final pattern = RegExp('^$basePathPattern\\[$indexToRemove\\]');
    return pattern.hasMatch(fieldName);
  }

  // Helper: get all keys with the index to remove
  List<String> getFieldsWithIndex(Map<String, dynamic> obj) {
    return obj.keys.where(isFieldInTargetSection).toList();
  }

  // Delete all values/options/errors/etc. for the section being removed
  for (final fieldName in getFieldsWithIndex(values)) {
    values.remove(fieldName);
  }
  for (final fieldName in getFieldsWithIndex(options)) {
    options.remove(fieldName);
  }
  for (final fieldName in getFieldsWithIndex(errors)) {
    errors.remove(fieldName);
  }
  for (final fieldName in getFieldsWithIndex(touched)) {
    touched.remove(fieldName);
  }
  for (final fieldName in getFieldsWithIndex(dependentValues)) {
    dependentValues.remove(fieldName);
  }
  for (final fieldName in getFieldsWithIndex(fieldsDisabled)) {
    fieldsDisabled.remove(fieldName);
  }

  // Now shift all higher indices down by one
  void updateKeys(Map<String, dynamic> obj) {
    final keys = obj.keys.toList();
    for (final key in keys) {
      final match =
          RegExp('^($basePathPattern)\\[(\\d+)\\](.*)\$').firstMatch(key);
      if (match != null) {
        final prefix = match.group(1)!;
        final index = int.parse(match.group(2)!);
        final suffix = match.group(3)!;
        if (index > indexToRemove) {
          final newKey = '$prefix[${index - 1}]$suffix';
          obj[newKey] = obj[key];
          obj.remove(key);
        }
      }
    }
  }

  updateKeys(values);
  updateKeys(options);
  updateKeys(errors);
  updateKeys(touched);
  updateKeys(dependentValues);
  updateKeys(fieldsDisabled);

  // Update allFields (remove and shift)
  allFields = removeFieldAtIndex(allFields, indexToRemove);

  notifyListeners();
}