Is there a way to set the field state to readonly using like setFieldState #11434
Unanswered
pchvramesh
asked this question in
General
Replies: 1 comment
-
Did you come up with a solution? I'm using shadcn's form components and did the following. (where // components/ui/shadcn/form.tsx
...
interface FormFieldProps<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> extends ControllerProps<TFieldValues, TName> {
readPermission?: PermissionLevel[];
userPermission?: PermissionLevel[];
writePermission?: PermissionLevel[];
}
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: FormFieldProps<TFieldValues, TName>) => {
const name = useMemo(() => ({ name: props.name }), [props.name]);
/**
* If fieldPermission and userPermission exist,
* check the user's permissions
* If the user does not have permission render null
*/
if (
props.readPermission &&
props.userPermission &&
!checkPermission(props.readPermission, props.userPermission)
)
return null;
/**
* If fieldPermission and userPermission exist,
* check the user's permissions
* If the user does not have write permission set isReadOnly
* to true, which causes the <fieldset>'s disabled attribute
* to be set
*/
const isReadOnly =
props.writePermission && props.userPermission
? !checkPermission(props.writePermission, props.userPermission)
: false;
return (
<FormFieldContext.Provider value={name}>
<fieldset disabled={isReadOnly}>
<Controller {...props} />
</fieldset>
</FormFieldContext.Provider>
);
};
... Then, inside my actual forms, I only need to add the code once and it will take care of not displaying the field at all, or making it readOnly ...
<FormField
control={form.control}
name="userName"
readPermission={["org:telemarketing:read"]}
render={({ field }) => {
return (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage></FormMessage>
</FormItem>
);
}}
userPermission={user.permissions}
writePermission={["org:telemarketing:manage"]}
/>
... |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I'm facing a situation where I need to set a field as read-only under certain conditions.
I've explored various tutorials on disabling fields using controller and making forms read-only by adjusting the form's state.
However, I haven't come across a suitable method for making a specific field readonly from component after calculations. Can someone guide me on the correct approach to fulfill this requirement?
Beta Was this translation helpful? Give feedback.
All reactions