Append fields that aren't in the form during submission? Remix+zod #276
-
I'm sort of answering my own question, but I'm curious if there's another intended way for this to work. When I'm making zod schemas for my forms, I only want the fields that have inputs to be on the schema and in the DOM because my form is only concerned with validating the user input, not other data that might be in the system. If validation fails for some reason on values that aren't displayed on the screen, there's nowhere for the user to see feedback, and there's nothing they can do about it anyway. The form should be allowed to be submitted if it is valid, and errors about other invalid state should be communicated elsewhere in the system, like a toast or something, "couldn't update the title because something else went wrong that has nothing to do with what you entered in this form". Example: A form that edits your blog post title, but the blog object has a lot of other stuff on it. The only input in the form is for the title, but when I submit the form, I need to put the blog post ID into the form data so the Remix action handler knows which one to update. const post = useLoaderData<BlogPost>();
const fetcher = useFetcher();
const [form, {title}] = useForm({
lastSubmission: fetcher.data,
onValidate({formData}) {
return parse(formData, {schema: UpdateTitleSchema});
},
onSubmit(event, {formData}) {
event.preventDefault();
formData.set('id', post.id);
fetcher.submit(formData, {
method: 'PUT'
});
}
}); This is a mega simplified contrived example. In reality I have some forms that are wizards and each page has a subset of the fields on it, but when I submit and move to the next page I need to submit the whole object with values from all pages, and overwrite them with the subset of values from the current page. Merging the object with the new FormData({
...post,
...Object.fromEntries(formData.entries())
}); 🤷 With RHF I do something like Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Now that I think about it, there would need to be separate schemas for server and client if I wanted to do it this way. The server will have more stuff on its formData than the client will in |
Beta Was this translation helpful? Give feedback.
That's how I will do as well. It's better to avoid sending data that you already know and limit itto fields that you allow your user to change. e.g. you can create a sub-schema by picking fields you actually accepted and reconstruct the object later by querying the rest of the fields from db.