File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -1288,6 +1288,15 @@ export class FieldApi<
12881288 this . triggerOnChangeListener ( )
12891289 }
12901290
1291+ /**
1292+ * Clear all values from the array.
1293+ */
1294+ clearValues = ( opts ?: UpdateMetaOptions ) => {
1295+ this . form . clearFieldValues ( this . name , opts )
1296+
1297+ this . triggerOnChangeListener ( )
1298+ }
1299+
12911300 /**
12921301 * @private
12931302 */
Original file line number Diff line number Diff line change @@ -1962,6 +1962,32 @@ export class FormApi<
19621962 this . validateField ( `${ field } [${ index2 } ]` as DeepKeys < TFormData > , 'change' )
19631963 }
19641964
1965+ /**
1966+ * Clear all values within an array field.
1967+ */
1968+ clearFieldValues = < TField extends DeepKeys < TFormData > > (
1969+ field : TField ,
1970+ opts ?: UpdateMetaOptions ,
1971+ ) => {
1972+ const fieldValue = this . getFieldValue ( field )
1973+
1974+ const lastIndex = Array . isArray ( fieldValue )
1975+ ? Math . max ( ( fieldValue as unknown [ ] ) . length - 1 , 0 )
1976+ : null
1977+
1978+ this . setFieldValue ( field , [ ] as any , opts )
1979+
1980+ if ( lastIndex !== null ) {
1981+ for ( let i = 0 ; i <= lastIndex ; i ++ ) {
1982+ const fieldKey = `${ field } [${ i } ]`
1983+ this . deleteField ( fieldKey as never )
1984+ }
1985+ }
1986+
1987+ // validate array change
1988+ this . validateField ( field , 'change' )
1989+ }
1990+
19651991 /**
19661992 * Resets the field value and meta to default state
19671993 */
Original file line number Diff line number Diff line change @@ -1195,6 +1195,9 @@ describe('field api', () => {
11951195
11961196 field . moveValue ( 0 , 1 )
11971197 expect ( arr ) . toStrictEqual ( [ 'middle' , 'end' , 'start' ] )
1198+
1199+ field . clearValues ( )
1200+ expect ( arr ) . toStrictEqual ( [ ] )
11981201 } )
11991202
12001203 it ( 'should reset the form on a listener' , ( ) => {
Original file line number Diff line number Diff line change @@ -3015,4 +3015,26 @@ describe('form api', () => {
30153015 form . parseValuesWithSchemaAsync ( z . any ( ) )
30163016 } ) . not . toThrowError ( )
30173017 } )
3018+
3019+ it ( 'should delete fields when resetting an array field to an empty array' , ( ) => {
3020+ const employees = [
3021+ {
3022+ firstName : 'Darcy' ,
3023+ } ,
3024+ ] as const
3025+
3026+ const form = new FormApi ( {
3027+ defaultValues : {
3028+ employees,
3029+ } ,
3030+ } )
3031+ form . mount ( )
3032+
3033+ form . clearFieldValues ( 'employees' )
3034+
3035+ expect ( form . getFieldValue ( 'employees' ) ) . toEqual ( [ ] )
3036+ expect ( form . getFieldValue ( `employees[0]` ) ) . toBeUndefined ( )
3037+ expect ( form . getFieldMeta ( `employees[0]` ) ) . toBeUndefined ( )
3038+ expect ( form . state . values . employees ) . toStrictEqual ( [ ] )
3039+ } )
30183040} )
You can’t perform that action at this time.
0 commit comments