2021-05-06 18:59:00 +00:00
|
|
|
import { Switch } from "@patternfly/react-core";
|
2023-01-26 09:31:07 +00:00
|
|
|
import { Controller, useFormContext } from "react-hook-form";
|
2022-12-21 17:39:24 +00:00
|
|
|
import { useTranslation } from "react-i18next";
|
2021-05-06 18:59:00 +00:00
|
|
|
|
|
|
|
import { FieldProps, FormGroupField } from "./FormGroupField";
|
|
|
|
|
|
|
|
type FieldType = "boolean" | "string";
|
|
|
|
|
|
|
|
type SwitchFieldProps = FieldProps & {
|
|
|
|
fieldType?: FieldType;
|
2024-02-26 15:29:38 +00:00
|
|
|
defaultValue?: string | boolean;
|
2021-05-06 18:59:00 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const SwitchField = ({
|
|
|
|
label,
|
|
|
|
field,
|
|
|
|
fieldType = "string",
|
|
|
|
isReadOnly = false,
|
2024-02-26 15:29:38 +00:00
|
|
|
defaultValue,
|
2021-05-06 18:59:00 +00:00
|
|
|
}: SwitchFieldProps) => {
|
2023-09-08 13:17:17 +00:00
|
|
|
const { t } = useTranslation();
|
2021-05-06 18:59:00 +00:00
|
|
|
const { control } = useFormContext();
|
|
|
|
return (
|
|
|
|
<FormGroupField label={label}>
|
|
|
|
<Controller
|
|
|
|
name={field}
|
2024-02-26 15:29:38 +00:00
|
|
|
defaultValue={
|
|
|
|
defaultValue ? defaultValue : fieldType === "string" ? "false" : false
|
|
|
|
}
|
2021-05-06 18:59:00 +00:00
|
|
|
control={control}
|
2022-12-21 17:39:24 +00:00
|
|
|
render={({ field }) => (
|
2021-05-06 18:59:00 +00:00
|
|
|
<Switch
|
|
|
|
id={label}
|
2023-09-14 09:01:15 +00:00
|
|
|
label={t("on")}
|
|
|
|
labelOff={t("off")}
|
2021-05-06 18:59:00 +00:00
|
|
|
isChecked={
|
2022-12-21 17:39:24 +00:00
|
|
|
fieldType === "string"
|
|
|
|
? field.value === "true"
|
|
|
|
: (field.value as boolean)
|
2021-05-06 18:59:00 +00:00
|
|
|
}
|
2024-04-05 14:37:05 +00:00
|
|
|
onChange={(_event, value) =>
|
2022-12-21 17:39:24 +00:00
|
|
|
field.onChange(fieldType === "string" ? "" + value : value)
|
2021-05-06 18:59:00 +00:00
|
|
|
}
|
2021-05-20 09:38:37 +00:00
|
|
|
isDisabled={isReadOnly}
|
2022-08-30 13:07:51 +00:00
|
|
|
aria-label={label}
|
2021-05-06 18:59:00 +00:00
|
|
|
/>
|
|
|
|
)}
|
|
|
|
/>
|
|
|
|
</FormGroupField>
|
|
|
|
);
|
|
|
|
};
|