flat-fuchsia
flat-fuchsia5mo ago

How can I get data from controller

import { Create } from "@refinedev/antd"; const PostCreate: React.FC = () => { return ( <Create saveButtonProps={{ size: "small", onClick: (e) => { e.preventDefault(); // Your custom function here } }}> <Controller name="production_role" control={control} defaultValue="" render={({ field }) => ( <> <Typography>Production Role</Typography> <Select {...field}> {production_roles.map((e: any) => ( <MenuItem value={e.uuid}>{e.name}</MenuItem> ))} </Select> </> )} /> <p>Rest of your page here</p> </Create> ); }; how can I get data from controller in Create component savebuttononclick function @kapa.ai
16 Replies
kapa.ai
kapa.ai5mo ago
Hi @Forever Knight. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To get data from the Controller in the Create component's saveButtonProps onClick function, you can use the getValues function from the useForm hook. The getValues function allows you to access the current form values. Here's an example of how you can use it:
import { useForm, Controller } from "react-hook-form";
import { Create } from "@refinedev/antd";

const PostCreate: React.FC = () => {
const { control, getValues } = useForm();

return (
<Create
saveButtonProps={{
size: "small",
onClick: (e) => {
e.preventDefault();
const formData = getValues();
console.log(formData.production_role);
// Your custom function here
},
}}
>
<Controller
name="production_role"
control={control}
defaultValue=""
render={({ field }) => (
<>
<Typography>Production Role</Typography>
<Select {...field}>
{production_roles.map((e: any) => (
<MenuItem value={e.uuid}>{e.name}</MenuItem>
))}
</Select>
</>
)}
/>
<p>Rest of your page here</p>
</Create>
);
};
import { useForm, Controller } from "react-hook-form";
import { Create } from "@refinedev/antd";

const PostCreate: React.FC = () => {
const { control, getValues } = useForm();

return (
<Create
saveButtonProps={{
size: "small",
onClick: (e) => {
e.preventDefault();
const formData = getValues();
console.log(formData.production_role);
// Your custom function here
},
}}
>
<Controller
name="production_role"
control={control}
defaultValue=""
render={({ field }) => (
<>
<Typography>Production Role</Typography>
<Select {...field}>
{production_roles.map((e: any) => (
<MenuItem value={e.uuid}>{e.name}</MenuItem>
))}
</Select>
</>
)}
/>
<p>Rest of your page here</p>
</Create>
);
};
In this example, getValues() is used to get the current form data, and formData.production_role is used to access the value of the production_role field. Please note that the code provided is a general example and may need to be adjusted to fit your specific use case. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@484585406495588352> kapa.ai is still learning and improving, please let us know how it did by reacting below
flat-fuchsia
flat-fuchsia5mo ago
send that form data to dataprovider using useCreate @kapa.ai
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To send the form data to the dataProvider using the useCreate hook, you can use the mutate method returned by useCreate. The mutate method expects values and resource as parameters, which will be passed to the create method from the dataProvider as parameters. Here's an example of how you can use it:
import { useForm, Controller } from "react-hook-form";
import { Create, useCreate } from "@refinedev/core";

const PostCreate: React.FC = () => {
const { control, getValues } = useForm();
const { mutate } = useCreate();

return (
<Create
saveButtonProps={{
size: "small",
onClick: (e) => {
e.preventDefault();
const formData = getValues();
mutate({
resource: "posts", // replace with your resource name
values: formData,
});
},
}}
>
<Controller
name="production_role"
control={control}
defaultValue=""
render={({ field }) => (
<>
<Typography>Production Role</Typography>
<Select {...field}>
{production_roles.map((e: any) => (
<MenuItem value={e.uuid}>{e.name}</MenuItem>
))}
</Select>
</>
)}
/>
<p>Rest of your page here</p>
</Create>
);
};
import { useForm, Controller } from "react-hook-form";
import { Create, useCreate } from "@refinedev/core";

const PostCreate: React.FC = () => {
const { control, getValues } = useForm();
const { mutate } = useCreate();

return (
<Create
saveButtonProps={{
size: "small",
onClick: (e) => {
e.preventDefault();
const formData = getValues();
mutate({
resource: "posts", // replace with your resource name
values: formData,
});
},
}}
>
<Controller
name="production_role"
control={control}
defaultValue=""
render={({ field }) => (
<>
<Typography>Production Role</Typography>
<Select {...field}>
{production_roles.map((e: any) => (
<MenuItem value={e.uuid}>{e.name}</MenuItem>
))}
</Select>
</>
)}
/>
<p>Rest of your page here</p>
</Create>
);
};
In this example, mutate is used to send the form data to the dataProvider. The resource parameter should be replaced with the name of your resource. The values parameter is the form data that you want to send. Please note that the code provided is a general example and may need to be adjusted to fit your specific use case. For more information, refer to the useCreate documentation (https://refine.dev/docs/data/hooks/use-create). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@484585406495588352> kapa.ai is still learning and improving, please let us know how it did by reacting below
flat-fuchsia
flat-fuchsia5mo ago
interface IUser { name: string; avatar: string; } export const Header: React.FC<RefineThemedLayoutV2HeaderProps> = ({ sticky = true, }) => { const { mode, setMode } = useContext(ColorModeContext); const { locale: currentLocale, locales, pathname, query } = useRouter(); const { data: user } = useGetIdentity<IUser>(); console.log(mode); return ( <AppBar position={sticky ? "sticky" : "relative"}> <Toolbar> <Stack direction="row" width="100%" alignItems="center"> <HamburgerMenu /> <Stack direction="row" width="100%" justifyContent="flex-end" alignItems="center" gap="16px" > <IconButton color="inherit" onClick={() => { setMode(); }} > {mode === "dark" ? <LightModeOutlined /> : <DarkModeOutlined />} </IconButton> {(user?.avatar || user?.name) && ( <Stack direction="row" gap="16px" alignItems="center" justifyContent="center" > {user?.name && ( <Typography sx={{ display: { xs: "none", sm: "inline-block", }, }} variant="subtitle2" > {user?.name} </Typography> )} <Avatar src={user?.avatar} alt={user?.name} /> </Stack> )} </Stack> </Stack> </Toolbar> </AppBar> ); }; set dark mode as default @kapa.ai
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To set dark mode as default, you can modify the ColorModeContextProvider component in your contexts/index.tsx file. You need to set the initial state of the mode to "dark". Here's how you can do it:
export const ColorModeContextProvider: React.FC<PropsWithChildren> = ({ children }) => {
const colorModeFromLocalStorage = localStorage.getItem("colorMode");
const isSystemPreferenceDark = window?.matchMedia("(prefers-color-scheme: dark)").matches;

const systemPreference = isSystemPreferenceDark ? "dark" : "light";
const [mode, setMode] = useState(colorModeFromLocalStorage || "dark"); // set "dark" as default

useEffect(() => {
window.localStorage.setItem("colorMode", mode);
}, [mode]);

const setColorMode = () => {
if (mode === "light") {
setMode("dark");
} else {
setMode("light");
}
};

return (
<ColorModeContext.Provider
value={{
setMode: setColorMode,
mode,
}}
>
<ThemeProvider theme={mode === "light" ? RefineThemes.Blue : RefineThemes.BlueDark}>{children}</ThemeProvider>
</ColorModeContext.Provider>
);
};
export const ColorModeContextProvider: React.FC<PropsWithChildren> = ({ children }) => {
const colorModeFromLocalStorage = localStorage.getItem("colorMode");
const isSystemPreferenceDark = window?.matchMedia("(prefers-color-scheme: dark)").matches;

const systemPreference = isSystemPreferenceDark ? "dark" : "light";
const [mode, setMode] = useState(colorModeFromLocalStorage || "dark"); // set "dark" as default

useEffect(() => {
window.localStorage.setItem("colorMode", mode);
}, [mode]);

const setColorMode = () => {
if (mode === "light") {
setMode("dark");
} else {
setMode("light");
}
};

return (
<ColorModeContext.Provider
value={{
setMode: setColorMode,
mode,
}}
>
<ThemeProvider theme={mode === "light" ? RefineThemes.Blue : RefineThemes.BlueDark}>{children}</ThemeProvider>
</ColorModeContext.Provider>
);
};
In this example, the initial state of mode is set to the value from local storage if it exists, otherwise, it defaults to "dark". This means that if there is no color mode set in local storage, the application will default to dark mode. Please note that the code provided is a general example and may need to be adjusted to fit your specific use case. For more information, refer to the Refine documentation (https://refine.dev/docs). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@484585406495588352> kapa.ai is still learning and improving, please let us know how it did by reacting below
flat-fuchsia
flat-fuchsia5mo ago
create: async ({ resource, variables, meta }) => { console.log(variables); let url = ${apiUrl}/${resource}/create; if (resource === "movie production member role") { url = ${apiUrl}/movieproductionmemberrole/create; } const { headers, method } = meta ?? {}; const requestMethod = (method as MethodTypesWithBody) ?? "post"; let mutatedata; if (resource === "movie production member role") { mutatedata = variables; } else { const { id, uuid, created_at, updated_at, edges, ...rest } = variables; mutatedata = rest; } // const { id, uuid, created_at, updated_at, edges, ...rest } = variables; const { data } = await httpClient[requestMethod](url, mutatedata, { headers, }); return { data: data.data, }; }, send formdata on httpClient @kapa.ai
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- In your provided code, you are already sending form data to the server using the httpClient in the create function. The httpClient is making a request to the url with the mutatedata as the body of the request. Here's the relevant part of your code:
const { data } = await httpClient[requestMethod](url, mutatedata, {
headers,
});
const { data } = await httpClient[requestMethod](url, mutatedata, {
headers,
});
In this line, httpClient[requestMethod] is making a request to the url. The requestMethod is determined by the method property of meta, and defaults to "post" if method is not provided. The mutatedata is the body of the request, and headers are the headers of the request. If you want to modify the form data before it is sent to the API, you can do so in the mutatedata variable. For example, if you want to add a field to the form data, you can do so like this:
mutatedata = { ...rest, newField: 'newValue' };
mutatedata = { ...rest, newField: 'newValue' };
This will add a newField with the value of 'newValue' to the form data. Please note that the code provided is a general example and may need to be adjusted to fit your specific use case. For more information, refer to the Refine documentation (https://refine.dev/docs). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
flat-fuchsia
flat-fuchsia5mo ago
I want to send it as a form-data @kapa.ai
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To send data as multipart/form-data using httpClient, you need to create a FormData object and append your data to it. Then, you can pass this FormData object as the body of your request. Here's an example of how you can do it:
const formData = new FormData();
Object.keys(mutatedata).forEach(key => formData.append(key, mutatedata[key]));

const { data } = await httpClient[requestMethod](url, formData, {
headers: {
...headers,
'Content-Type': 'multipart/form-data',
},
});
const formData = new FormData();
Object.keys(mutatedata).forEach(key => formData.append(key, mutatedata[key]));

const { data } = await httpClient[requestMethod](url, formData, {
headers: {
...headers,
'Content-Type': 'multipart/form-data',
},
});
In this example, a FormData object is created and each key-value pair in mutatedata is appended to it. This FormData object is then passed as the body of the request. The 'Content-Type' header is set to 'multipart/form-data' to indicate that the request body contains form data. Please note that the code provided is a general example and may need to be adjusted to fit your specific use case. For more information, refer to the Refine documentation (https://refine.dev/docs). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@484585406495588352> kapa.ai is still learning and improving, please let us know how it did by reacting below
kapa.ai
kapa.ai5mo ago
Sorry @Forever Knight, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist: Perhaps try again in 15mins?
flat-fuchsia
flat-fuchsia5mo ago
create: async ({ resource, variables, meta }) => { console.log(variables); let url = ${apiUrl}/${resource}/create; if (resource === "movie production member role") { url = ${apiUrl}/movieproductionmemberrole/create; } const { headers, method } = meta ?? {}; const requestMethod = (method as MethodTypesWithBody) ?? "post"; let mutatedata; if (resource === "movie production member role") { mutatedata = variables; } else { const { id, uuid, created_at, updated_at, edges, ...rest } = variables; mutatedata = JSON.stringify(rest); } console.log(mutatedata); const { data } = await httpClient[requestMethod](url, mutatedata, { headers: { ...headers, "Content-Type": "multipart/form-data", }, }); return { data: data.data, }; }, how do i send JSON data from form-data @kapa.ai
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: @Forever Knight That's a great question, but unfortunately I am only capable of responding to a maximum of five questions per thread. Don't hesitate to create a new thread for any further questions you have though. I'm here to help!