Skip to content

Make a standard way of handling 'add/remove subform on value changed' #34

@piotruela

Description

@piotruela

There is a quite common case in which we want to add different type of subform based on the selected value in the parent form.

enum Type { url, document, page }

class ItemFormCubit extends FormGroupCubit {
  ItemFormCubit()
    : typeField = SingleSelectFieldCubit<Type?, ValidationError>(
        initialValue: Type.url,
        validator: Validators.requiredFieldValidator,
        options: Type.values,
      ),

      urlItemFormCubit = UrlItemFormCubit(),
      fileItemFormCubit = FileItemFormCubit() {
    registerFields([typeField]);

    typeField.stream.distinct().listen((data) => _onTypeUpdated(data.value));
  }

  final SingleSelectFieldCubit<Type?, ValidationError> typeField;
  final UrlItemFormCubit urlItemFormCubit;
  final FileItemFormCubit fileItemFormCubit;

  Future<void> _onTypeUpdated(Type? type) async {
    if (type == Type.url) {
      addSubform(UrlItemFormCubit());
    } else {
      urlItemFormCubit.resetAll();
      await removeSubform(urlItemFormCubit, close: false);
    }

    if (type == Type.document) {
      addSubform(fileItemFormCubit);
    } else {
      fileItemFormCubit.resetAll();
      await removeSubform(fileItemFormCubit, close: false);
    }
  }
}

We should find a way to handle those cases in more robust way

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions