mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Form: Allow default values updates (#22435)
* Allow default values update in form * Update packages/grafana-ui/src/components/Forms/Form.story.tsx
This commit is contained in:
parent
712253fbee
commit
22ce16cc9b
@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { Legend } from './Legend';
|
||||
|
||||
import { withCenteredStory } from '../../utils/storybook/withCenteredStory';
|
||||
@ -122,17 +122,39 @@ export const basic = () => {
|
||||
};
|
||||
|
||||
export const defaultValues = () => {
|
||||
const defaultValues = [
|
||||
{
|
||||
name: 'Roger Waters',
|
||||
nested: {
|
||||
path: 'Nested path default value',
|
||||
},
|
||||
radio: 'option2',
|
||||
select: 'option1',
|
||||
switch: true,
|
||||
},
|
||||
{
|
||||
name: 'John Waters',
|
||||
nested: {
|
||||
path: 'Nested path default value updated',
|
||||
},
|
||||
radio: 'option1',
|
||||
select: 'option2',
|
||||
switch: false,
|
||||
},
|
||||
];
|
||||
const [defaultsIdx, setDefaultsIdx] = useState(0);
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderForm({
|
||||
name: 'Roger Waters',
|
||||
nested: {
|
||||
path: 'Nested path default value',
|
||||
},
|
||||
radio: 'option2',
|
||||
select: 'option1',
|
||||
switch: true,
|
||||
})}
|
||||
{renderForm(defaultValues[defaultsIdx])}
|
||||
<Button
|
||||
onClick={() => {
|
||||
setDefaultsIdx(s => (s + 1) % 2);
|
||||
}}
|
||||
variant="secondary"
|
||||
>
|
||||
Change default values
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -2,7 +2,7 @@
|
||||
* This is a stub implementation only for correct styles to be applied
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm, Mode, OnSubmit, DeepPartial, FormContextValues } from 'react-hook-form';
|
||||
import { GrafanaTheme } from '@grafana/data';
|
||||
import { css } from 'emotion';
|
||||
@ -27,10 +27,17 @@ interface FormProps<T> {
|
||||
|
||||
export function Form<T>({ validateOn, defaultValues, onSubmit, children }: FormProps<T>) {
|
||||
const theme = useTheme();
|
||||
const { handleSubmit, register, errors, control } = useForm<T>({
|
||||
const { handleSubmit, register, errors, control, reset, getValues } = useForm<T>({
|
||||
mode: validateOn || 'onSubmit',
|
||||
defaultValues,
|
||||
defaultValues: {
|
||||
...defaultValues,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
reset({ ...getValues(), ...defaultValues });
|
||||
}, [defaultValues]);
|
||||
|
||||
const styles = getFormStyles(theme);
|
||||
|
||||
return (
|
||||
|
Loading…
Reference in New Issue
Block a user