Fixed #7046 and #7049 - Form: Request to expose functionality to code such as .reset() , .validate(), .submit(), etc

pull/7060/head
Mert Sincan 2025-01-08 10:40:56 +00:00
parent f5e43eb567
commit 3b70777c90
2 changed files with 52 additions and 1 deletions

View File

@ -11,6 +11,7 @@ import type { DefineComponent, DesignToken, EmitFn, PassThrough } from '@primevu
import type { ComponentHooks } from '@primevue/core/basecomponent';
import { VNode } from 'vue';
import type { PassThroughOptions } from '../types';
import { useFormFieldState } from '../useform';
export declare type FormPassThroughOptionType = FormPassThroughAttributes | ((options: FormPassThroughMethodOptions) => FormPassThroughAttributes | string) | string | null | undefined;
@ -267,6 +268,48 @@ export interface FormEmitsOptions {
export declare type FormEmits = EmitFn<FormEmitsOptions>;
export interface FormFieldState extends useFormFieldState {}
export interface FormInstance {
/**
* Set the value of a form field.
* @param field field name
* @param value field value
*/
setFieldValue: (field: string, value: any) => void;
/**
* Validates the form or a specific field.
* @param field
* @returns
*/
validate: (field?: string | string[]) => Promise<{
values?: any;
errors: any;
}>;
/**
* Sets the values of the form fields.
* @param values
*/
setValues: (values: Record<string, any>) => void;
/**
* Resets the entire form state, clearing values and validation statuses.
*/
reset: () => void;
/**
* Submits the form.
* @returns
*/
submit: () => void;
/**
* Whether the form is valid.
*/
valid: boolean;
/**
* The state of each form field, with the field name as the key and its state as the value.
*/
states: Record<string, FormFieldState>;
}
/**
* **PrimeVue - Form**
*

View File

@ -1,5 +1,5 @@
<template>
<form @submit.prevent="onSubmit" @reset.prevent="onReset" :class="cx('root')" v-bind="ptmi('root')">
<form ref="formRef" @submit.prevent="onSubmit" @reset.prevent="onReset" :class="cx('root')" v-bind="ptmi('root')">
<slot :register :valid :reset v-bind="states" />
</form>
</template>
@ -7,6 +7,7 @@
<script>
import { omit } from '@primeuix/utils';
import { useForm } from '@primevue/forms/useform';
import { ref } from 'vue';
import BaseForm from './BaseForm.vue';
export default {
@ -15,8 +16,13 @@ export default {
inheritAttrs: false,
emits: ['submit', 'reset'],
setup(props, { emit }) {
const formRef = ref(null);
const $form = useForm(props);
const submit = () => {
formRef.value?.requestSubmit();
};
const register = (field, options) => {
const [, fieldProps] = $form.defineField(field, options);
@ -32,6 +38,8 @@ export default {
});
return {
formRef,
submit,
register,
onSubmit,
onReset,