FIX: allows to manually remove error for virtual fields (#28555)

In FormKit you can add error on an existing field existing in the DOM, but you can also set an arbitrary error on a virtual field not existing in the DOM.

When revalidating existing data, we are only resetting real fields. This commit adds `removeError(name)` to allow you to manually manage virtual fields. `removeError` is available in the same helpers where `addError` is available.

<!-- NOTE: All pull requests should have tests (rspec in Ruby, qunit in JavaScript). If your code does not include test coverage, please include an explanation of why it was omitted. -->
This commit is contained in:
Joffrey JAFFEUX 2024-08-26 20:32:46 +02:00 committed by GitHub
parent d62c32ba71
commit 27f08a5c28
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 1 deletions

View File

@ -131,7 +131,7 @@ export default class AdminBadgesShowController extends Controller {
}
@action
validateForm(data, { addError }) {
validateForm(data, { addError, removeError }) {
if (!data.icon && !data.image_url) {
addError("icon", {
title: "Icon",
@ -141,6 +141,9 @@ export default class AdminBadgesShowController extends Controller {
title: "Image",
message: I18n.t("admin.badges.icon_or_image"),
});
} else {
removeError("image_url");
removeError("icon");
}
}

View File

@ -43,6 +43,7 @@ class FKForm extends Component {
submit: this.onSubmit,
reset: this.onReset,
addError: this.addError,
removeError: this.removeError,
});
this.router.on("routeWillChange", this.checkIsDirty);
@ -95,6 +96,11 @@ class FKForm extends Component {
});
}
@action
removeError(name) {
this.formData.removeError(name);
}
@action
async addItemToCollection(name, value = {}) {
const current = this.formData.get(name) ?? [];
@ -221,6 +227,7 @@ class FKForm extends Component {
await this.args.validate?.(this.formData.draftData, {
addError: this.addError,
removeError: this.removeError,
});
} finally {
this.isValidating = false;

View File

@ -237,4 +237,31 @@ module("Integration | Component | FormKit | Form", function (hooks) {
assert.dom(".foo").hasText("2");
assert.dom(".bar").hasText("2");
});
test("reset virtual errors", async function (assert) {
let validatedOnce = false;
const validate = async (data, { removeError, addError }) => {
if (!validatedOnce) {
addError("foo", { title: "Foo", message: "error" });
validatedOnce = true;
} else {
removeError("foo");
}
};
await render(<template>
<Form @validate={{validate}} as |form|>
<form.Submit />
</Form>
</template>);
await formKit().submit();
assert.form().hasErrors({ foo: "error" });
await formKit().submit();
assert.form().hasNoErrors();
});
});