How do you get a nested value item in ant design - reactjs

im quite new on reactJS and also ant design. right now im trying to get a value from a Form.List that i want to make it / render it as json nested data output.
my full code :
import { MinusCircleOutlined, PlusOutlined } from '#ant-design/icons';
import { Button, Form, Input, Space, DatePicker, Select } from 'antd';
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import Cookies from "js-cookies";
import moment from 'moment';
import 'moment/locale/zh-cn';
const Stockpickingnew = ({ title }) => {
const options = [
{
value: '1',
label: 'True',
},
{
value: '0',
label: 'False',
},
{
value: '7',
label: 'product_tmpl_id'
},
];
const Navigate = useNavigate()
const dateFormat = ['DD-MM-YYYY'];
//---------------------------------------------------------------------------------------------------------------
let headers = {
"Authorization": "Bearer " + Cookies.getItem('access_token')
}
const onFinish = (values) => {
console.log('Success:', values);
let stockpick = {
date: moment(values.date).format("DD-MM-YYYY"),
origin: values.origin,
picking_type_id: values.picking_type_id,
location_id: values.location_id,
location_dest_id: values.location_dest_id,
stock_move_ids: [{
demand: values.demand,
done: values.done,
product_uom: values.product_uom,
product_tmpl_id: values.product_tmpl_id,
}]
};
console.log(JSON.stringify(stockpick))
let params = JSON.stringify(stockpick)
axios.post('http://127.0.0.1:5000/api/stockpickings', params, { headers })
.then(() => {
Navigate('/')
})
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
//---------------------------------------------------------------------------------------------------------------
return (
<>
<div className='new'>
<div className="top">
<h1>{title}</h1>
</div>
<div className="bottom">
<div className="stockPicking">
<Form
name="stockPickings"
layout="vertical"
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<div className="left">
<Form.Item
label="Origin :"
name='origin'
>
<Select
options={options}
placeholder="Origin"
/>
</Form.Item>
<Form.Item
label="Picking Type :"
name='picking_type_id'
>
<Select
options={options}
placeholder="Picking Type"
/>
</Form.Item>
<Form.Item
label="Date :"
name='date'
>
<DatePicker
format={dateFormat}
onChange={(dateInMomentFormat, dateInStringFormat) => {
console.log(dateInStringFormat);
}}
/>
</Form.Item>
</div>
<div className="right">
<Form.Item
label="Location :"
name='location_id'
>
<Select
options={options}
placeholder="Location"
/>
</Form.Item>
<Form.Item
label="Destination :"
name='location_dest_id'
>
<Select
options={options}
placeholder="Destination"
/>
</Form.Item>
</div>
<div className="stockMove">
<Form.Item>
<Form.List name="stock_move_ids">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Space
key={field.key}
style={{
display: 'flex',
marginBottom: 8,
}}
align="baseline"
>
<Form.Item
{...field}
name={[field.name, 'demand']}
key={[field.key, 'demand']}
rules={[
{
required: true,
message: 'Missing Demand',
},
]}
>
<Input placeholder="Demand" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'done']}
key={[field.key, 'done']}
>
<Select
options={options}
placeholder="Done"
/>
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'product_uom']}
key={[field.key, 'product_uom']}
rules={[
{
required: true,
message: 'Missing product_uom',
},
]}
>
<Select
options={options}
placeholder="product_uom"
/>
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'product_tmpl_id']}
key={[field.key, 'product_tmpl_id']}
rules={[
{
required: true,
message: 'Missing product_tmpl_id',
},
]}
>
<Select
options={options}
placeholder="product_tmpl_id"
/>
</Form.Item>
<MinusCircleOutlined onClick={() => remove(field.name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
Add field
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form.Item>
</div>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</div>
</div>
</div>
</>
)
}
export default Stockpickingnew
im sorry if it's really hard to read but basically, what i really want to do is my Form.List can get a value as nested data like :
stock_move_ids: [{
demand: values.demand,
done: values.done,
product_uom: values.product_uom,
product_tmpl_id: values.product_tmpl_id,
}]
my console.log (values) and console.log JSON.stringify(stockpick) do have different result as image below.
first one is from console.log values and the bottom one is from console.log stockpick
Screenshoot here

stock_move_ids values have 0th index you can access it like this.
let stockpick = {
date: moment(values.date).format("DD-MM-YYYY"),
origin: values.origin,
picking_type_id: values.picking_type_id,
location_id: values.location_id,
location_dest_id: values.location_dest_id,
stock_move_ids: [
{
demand: values?.stock_move_ids?.[0]?.demand,
done: values?.stock_move_ids?.[0]?.done,
product_uom: values?.stock_move_ids?.[0]?.product_uom,
product_tmpl_id: values?.stock_move_ids?.[0]?.product_tmpl_id,
},
],
};

Related

Why am i POST a lot of unwanted data?

I'm kind of new with java and ReactJS and I have a big issue where when I tried to post my data, it posted a lot of unwanted data like rendering the whole table.
My console.log() printed this :
location_dest_id: 2
location_id: 1
origin: "test3"
picking_type_id: 1
stock_move_ids: Array(1)
0:
altKey: false
bubbles: true
button: 0
buttons: 0
cancelable: true
clientX: 317
clientY: 652
ctrlKey: false
currentTarget: null
defaultPrevented: false
demand: "12"
detail: 1
done: "0"
eventPhase: 3
getModifierState: ƒ modifierStateGetter(keyArg)
isDefaultPrevented: ƒ functionThatReturnsFalse()
isPropagationStopped: ƒ functionThatReturnsFalse()
isTrusted: true
metaKey: false
movementX: 0
movementY: 0
nativeEvent: PointerEvent {isTrusted: true, pointerId: 1, width: 1,
height: 1, pressure: 0, …}
pageX: 317
pageY: 754
product_tmpl_id: 9
product_uom: "1"
relatedTarget: null
screenX: 317
screenY: 723
shiftKey: false
target: span
timeStamp: 203547.59999990463
type: "click"
view: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
_reactName: "onClick"
_targetInst: null
From what I understand, the error is when I tried to pass "stock_move_ids" nested data, it POST so much data as like the console.log() above. What it should be passed is like this :
[
{
"date":"02-09-2022",
"origin":"test2",
"picking_type_id":2,
"location_id":1,
"location_dest_id":2,
"stock_move_ids":
[
{
"demand":12,
"done":0,
"product_uom":1,
"product_tmpl_id":18
}
]
}
]
Is there any way to solve my problem? My code is based on this template : https://codesandbox.io/s/j0opp
Here's my code looks like :
Parent
import React, { useEffect, useContext } from "react";
import { Button, Form, Input, DatePicker, Select } from 'antd';
import { Stockmovetable } from "./Stockmovetable";
import { AppContext } from '../../../context/Appcontext'
const Stockpickingnew = ({ title }) => {
const { Function, State } = useContext(AppContext)
const { fetchDataPickingType, fetchDataLocation, fetchDataPupuk, option, stock_move_ids, StockPick, StockPickFailed } = Function
const { dateFormat, dataPupuk, dataStockLocation, dataStockPickingType } = State
useEffect(() => {
fetchDataPickingType()
fetchDataLocation()
fetchDataPupuk()
}, [])
return (
<>
<div className='new'>
<div className="top">
<h1>{title}</h1>
</div>
<div className="bottom">
<div className="stockPicking">
<Form
name="stockPickings"
layout="vertical"
onFinish={StockPick}
onFinishFailed={StockPickFailed}
autoComplete="off"
>
<div className="left">
<Form.Item
label="Origin :"
name='origin'
>
<Input placeholder="Origin" />
</Form.Item>
<Form.Item
label="Picking Type :"
name='picking_type_id'
>
<Select
placeholder="Picking Type"
options={dataStockPickingType.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
<Form.Item
label="Date :"
name='date'
>
<DatePicker
format={dateFormat}
/>
</Form.Item>
</div>
<div className="right">
<Form.Item
label="Location :"
name='location_id'
>
<Select
placeholder="Tujuan Awal"
options={dataStockLocation.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
<Form.Item
label="Destination :"
name='location_dest_id'
>
<Select
placeholder="Tujuan Akhir"
options={dataStockLocation.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
</div>
<div className="stockMove">
<Form.List name="stock_move_ids">
{(stock_move_ids, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
</div>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</div>
</div>
</div>
</>
)
}
export default Stockpickingnew
Child
import React from "react";
import { Form, Input, Button, Table, Select } from "antd";
import { PlusOutlined, MinusOutlined } from "#ant-design/icons";
const { Column } = Table;
export const Stockmovetable = props => {
const { stock_move_ids, add, remove, dataPupuk, option } = props;
return (
<Table
dataSource={stock_move_ids}
pagination={false}
footer={() => {
return (
<Form.Item>
<Button onClick={add}>
<PlusOutlined /> Add field
</Button>
</Form.Item>
);
}}
>
<Column
dataIndex={"product_tmpl_id"}
title={"Nama Produk"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "product_tmpl_id"]}>
<Select
placeholder="Produk"
options={dataPupuk.map(e => ({ label: e.name, value: e.id }))}
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"demand"}
title={"Demand"}
render={(value, row, index) => {
// console.log(row);
return (
<Form.Item name={[index, "demand"]}>
<Input
placeholder="Demand"
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"done"}
title={"Done"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "done"]}>
<Select
placeholder="Tujuan Akhir"
options={option}
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"product_uom"}
title={"product_uom"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "product_uom"]}>
<Input
placeholder="product_uom"
/>
</Form.Item>
);
}}
/>
<Column
title={"Action"}
render={(value, row, index) => {
return (
<React.Fragment>
<Button
icon={<MinusOutlined />}
shape={"circle"}
onClick={() => remove(row.name)}
/>
</React.Fragment>
);
}}
/>
</Table>
);
};
Context
export const AppContext = createContext()
export const AppProvider = props => {
const Navigate = useNavigate()
const dateFormat = ['DD-MM-YYYY'];
const StockPick = (values) => {
console.log('Success:', values);
let stockpick = [{
date: moment(values.date).format("DD-MM-YYYY"),
origin: values.origin,
picking_type_id: values.picking_type_id,
location_id: parseInt(values.location_id),
location_dest_id: parseInt(values.location_dest_id),
stock_move_ids: [
{
demand: parseInt(values?.stock_move_ids?.[0]?.demand),
done: parseInt(values?.stock_move_ids?.[0]?.done),
product_uom: parseInt(values?.stock_move_ids?.[0]?.product_uom),
product_tmpl_id: values?.stock_move_ids?.[0]?.product_tmpl_id,
},
],
}];
let params = JSON.stringify(stockpick)
console.log(params)
axios.post('http://127.0.0.1:5000/api/stockpickings', params, { headers })
.then(() => {
Navigate('/')
})
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
};
}
I think this is all I can provide / needed to fix my codings, if there's anything I need to add and or fix, please tell me. Thank you.
Okay after some hours tries
as the comment above, i think all i need to do is just not making the body as dataindex.
from :
<Form.List name="stock_move_ids">
{(stock_move_ids, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
to
<Form.List name="stock_move_ids">
{(stock_move, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
Thank you very much for the helps!

Change date format in antd <DatePicker />

I'm submitting a form to send data to my API that receives date in the format of YYYY-MM-DD but by default the DatePicker component keeps adding extra characters of time to the end of the date, for example when I enter a date for my date of birth field the value is stored in the format below
{
"date_of_birth":"2003-02-03T13:32:49.543Z"
}
I would prefer it to be just
{
"date_of_birth":"2003-02-03"
}
below is the code for the form and its submit function
const Demo = () => {
const [visible, setVisible] = useState(false);
const [form] = Form.useForm();
const showUserModal = () => {
setVisible(true);
};
const hideUserModal = () => {
setVisible(false);
};
const onFinish = values => {
console.log(JSON.stringify(values))
const userToken = localStorage.getItem(AUTH_TOKEN)
IndividualService.setToken(userToken)
IndividualService.postIndividual(values).then(resp => {
console.log(resp)
message.success('successfully added details for Individual plan')
}).catch(error => {
message.error('Error occured, plase try again', error.message)
})
};
const customFormat = value => `custom format: ${value.format("YYYY-MM-DD")}`;
return (
<Card title='Enter Customer details for individual plan'>
<Row justify='center'>
<Col span={20}>
<Form.Provider
onFormFinish={(name, { values, forms }) => {
if (name === 'userForm') {
const { basicForm } = forms;
const dependants = basicForm.getFieldValue('dependants') || [];
basicForm.setFieldsValue({
dependants: [...dependants],
...values
});
setVisible(false);
}
}}
>
<Form {...layout} name="basicForm" onFinish={onFinish} size='small'>
<Form.Item
name="first_name"
label="First Name"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="other_names"
label="Other Names"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select>
<Option value="MALE">male</Option>
<Option value="FEMALE">female</Option>
</Select>
</Form.Item>
<Form.Item
name="date_of_birth"
label="Date of Birth"
rules={[
{
required: true,
},
]}
>
<DatePicker format={customFormat} />
</Form.Item>
<Form.Item
name="blood_group"
label="Blood Group"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="residential_address"
label="Residential address"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="workplace_address"
label="Workplace address"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="additional_telephone_no"
label="Additional phone no."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="NIN"
label="NIN"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_name"
label="Next of kin name"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_telephone"
label="next of kin phone."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="next_of_kin_email"
label="next of kin email."
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="dependants"
label="Dependants List"
shouldUpdate={(prevValues, curValues) => prevValues.dependants !== curValues.dependants}
>
{({ getFieldValue }) => {
const dependants = getFieldValue('dependants') || [];
return dependants.length ? (
<ul>
{dependants.map((d, index) => (
<li key={index} className="user">
<Avatar icon={<UserOutlined />} />
<p>{d.first_name} - {d.relationship}</p>
</li>
))}
</ul>
) : (
<Typography.Text className="ant-form-text" type="secondary">
( <SmileOutlined /> No dependant yet. )
</Typography.Text>
);
}}
</Form.Item>
<Form.Item {...tailLayout}>
<Button htmlType="submit" type="primary">
Submit
</Button>
<Button
htmlType="button"
style={{
marginLeft: 8,
}}
onClick={showUserModal}
>
Add User
</Button>
</Form.Item>
</Form>
<ModalForm visible={visible} onCancel={hideUserModal} />
</Form.Provider>
</Col>
</Row>
</Card>
);
};
You can add the prop format to get the input in custom format, as
<DatePicker
format="YYYY-MM-DD"
/>
This will display the date in the format YYYY-MM-DD in the date picker.
To convert this to the required format you may need to format it in the onFinish , as:
const onFinish = values => {
console.log(JSON.stringify(values))
const userToken = localStorage.getItem(AUTH_TOKEN)
IndividualService.setToken(userToken)
values["date_of_birth"] = moment(values.date_of_birth).format("YYYY-MM-DD")
IndividualService.postIndividual(values).then(resp => {
console.log(resp)
message.success('successfully added details for Individual plan')
}).catch(error => {
message.error('Error occured, plase try again', error.message)
})
};

Store country names in ISO 3166 format in mongoDB

In my flight booking application the admin enters destination names while adding new flights. The admin can write the full country/City names (i.e. Sydney, New York etc.) But I want to save them as 3 letter abbreviation such as (SYD, NYC etc.) in the database when admin clicks the submit button. I tried using the i18n-iso-countries package but I'm not quite sure of implementing this. Is there any simple approach to this?
This is my form component:
import React, { useState } from "react";
import {
TextField,
FormControl,
InputLabel,
MenuItem,
Select,
RadioGroup,
FormControlLabel,
Radio,
Button,
} from "#mui/material";
import Autocomplete from "#mui/material/Autocomplete";
import DatePicker from "#mui/lab/DatePicker";
import AdapterDateFns from "#mui/lab/AdapterDateFns";
import LocalizationProvider from "#mui/lab/LocalizationProvider";
import SendIcon from "#mui/icons-material/Send";
import "./Form.css";
const destinations = [
{ title: "Sydney" },
{ title: "Paris" },
{ title: "Thailand" },
{ title: "France" },
{ title: "Dhaka" },
{ title: "Bangkok" },
{ title: "Indonesia" },
];
export default function Form() {
const dt = new Date().toLocaleDateString();
console.log(dt);
const [formData, setFormData] = useState({
from: "",
to: "",
depart: dt,
return: dt,
noOfPassenger: 1,
tripType: "Round Trip",
});
const defaultProps = {
options: destinations,
getOptionLabel: (option) => option.title,
};
const handleSubmit = () => {
if (formData.tripType === "One Way")
setFormData({ ...formData, return: "None" });
console.log(formData);
};
return (
<div className="form_parent">
<div className="inner_form">
<div className="from">
<Autocomplete
{...defaultProps}
onChange={(event, value) =>
setFormData({ ...formData, from: value.title })
}
renderInput={(params) => (
<TextField {...params} label="From" variant="outlined" required />
)}
/>
</div>
<div className="to">
<Autocomplete
{...defaultProps}
onChange={(event, value) =>
setFormData({ ...formData, to: value.title })
}
renderInput={(params) => (
<TextField {...params} label="To" variant="outlined" required />
)}
/>
</div>
<div className="dates">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Departure Date"
value={formData.depart}
disablePast
onChange={(e) =>
setFormData({
...formData,
depart: e.toLocaleDateString(),
})
}
renderInput={(params) => <TextField {...params} required />}
/>
</LocalizationProvider>
</div>
<div className="dates">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Return Date"
value={formData.return}
disablePast
disabled={formData.tripType === "One Way" ? true : false}
onChange={(e) =>
setFormData({
...formData,
return: e.toLocaleDateString(),
})
}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</div>
<div className="dates">
<FormControl className="passenger">
<InputLabel id="passengerNo">No. of Passenger</InputLabel>
<Select
variant="outlined"
labelId="passengerNo"
value={formData.noOfPassenger}
required
label="No. of Passenger"
onChange={(e) =>
setFormData({ ...formData, noOfPassenger: e.target.value })
}
>
<MenuItem value={1}>1</MenuItem>
<MenuItem value={2}>2</MenuItem>
<MenuItem value={3}>3</MenuItem>
<MenuItem value={4}>4</MenuItem>
</Select>
</FormControl>
</div>
<div className="radio_buttons">
<FormControl component="fieldset">
<RadioGroup
row
aria-label="trip"
name="row-radio-buttons-group"
value={formData.tripType}
onChange={(e) =>
setFormData({ ...formData, tripType: e.target.value })
}
>
<FormControlLabel
value="One Way"
control={<Radio />}
label="One Way"
/>
<FormControlLabel
value="Round Trip"
control={<Radio />}
label="Round Trip"
/>
</RadioGroup>
</FormControl>
</div>
<div className="submit">
<Button
className="submit_btn"
variant="contained"
color="error"
onClick={handleSubmit}
endIcon={<SendIcon />}
>
Submit
</Button>
</div>
</div>
</div>
);
}
Model
import mongoose from "mongoose";
const flightSchema = mongoose.Schema({
from: String,
to: String,
price: String,
flightType: String,
airline: String,
date: {
type: Date,
default: new Date().toLocaleDateString(),
},
});
const FlightData = mongoose.model("FlightData", flightSchema);
export default FlightData;

antd form field is not resetting for checkboxes

I have a antd form that consists of input and checkboxes.
antd : 4.16.0
react : 17.0.2
After using,
this.formRef.current.resetFields();
the input fields are getting reset but not the checkboxes.
Sample Code:
<Form
layout="vertical"
hideRequiredMark
initialValues={{
sunH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
monH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
}}
ref={this.props.formRef}
>
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="pName"
label="Name"
rules={[
{
required: true,
message: "Please enter Name",
},
]}
>
<Input placeholder="Enter name" />
</Form.Item>
<Form.Item name="Mon" label="" valuePropName="checked">
<Text>Mon</Text>
</Form.Item>
</Col>
</Row>
</Form>
the form takes in a onCancel props, so onCancel,
this.formRef.current.resetFields();
log of this.formRef.current:
you can manually set radio fields value null in that function ...
all you have to do is ...
formRef.setFieldsValue(['label_name(Mon)'] : undefined)
try formRef.current.setFieldsValue if you cant't change using upper code.
for functional component you have to take the form reference that is binding using useForm() and you have to call setfield method same.
form.setFieldsValue(['label_name(Mon)'] : undefined )
ant.design/components/form/#components-form-demo-nest-messages Check the second example, they have well explained everything you need there
https://codesandbox.io/s/form-methods-antd-4-17-0-alpha-7-forked-ff1uf?file=/index.js:0-2953
Check this working example with checkbox
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Select, Checkbox } from "antd";
const { Option } = Select;
const layout = {
labelCol: {
span: 8
},
wrapperCol: {
span: 16
}
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16
}
};
const Demo = () => {
const [form] = Form.useForm();
const onGenderChange = (value) => {
switch (value) {
case "male":
form.setFieldsValue({
note: "Hi, man!"
});
return;
case "female":
form.setFieldsValue({
note: "Hi, lady!"
});
return;
case "other":
form.setFieldsValue({
note: "Hi there!"
});
}
};
const onFinish = (values) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
note: "Hello world!",
gender: "male"
});
};
return (
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
<Form.Item
name="note"
label="Note"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true
}
]}
>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) =>
prevValues.gender !== currentValues.gender
}
>
{({ getFieldValue }) =>
getFieldValue("gender") === "other" ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
wrapperCol={{
offset: 8,
span: 16
}}
>
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
};

Antd Select not setting initial value

I have an issue in setting the initial value in antd Select
const options=[{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
<Form initialValues={{user:3}}>
<Form.Item name="user" label="Select user">
<Select value="3">
{options.map((user,index)=><Option key={index} value={user.id}>{user.name}</Option>)}
</Select>
</Form.Item>
</Form>
It's not selecting the initial value. Any idea in this. is this a correct way of implementing it, please help
The below is a simple demo of Select Component in Antd Form
I am wondering whether the options come from the store or other components? So the form does not get the initial values once the form is mounted. If it comes from other source, you need to subscribe the initial values if it changes to reset the antd form like
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox, Select } from 'antd';
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
// useEffect(() => {
// form.resetFields()
// form.setFieldsValue({
// productName: productName
// })
// }, [initialValues]);
const userNameOptions = [{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
const Demo = () => {
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
username: 3
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Select value='3'>
{userNameOptions.map((item, index) => (
<Select.Option key={index} value={item.id}>
{item.name}
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item {...tailLayout} name="remember" valuePropName="checked">
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
I have this working in ant design 4.
If you only need to set the value once use defaultValue and pass a string prop
defaultValue={!!props.DefaultString && claimId}
You can however set the values for both the current value and the options by using form.setFieldsValue in useEffect.
e.g.
useEffect(() => {
form.setFieldsValue({
SelectValue: !!props.selectItemValue && props.props.claimId,
SelectableOptions: (!!props.selectableOptions? props.selectableOptions : undefined)
);
}
}, [props,form]);
<Form.Item name="SelectValue" >
<Select >
{!!props.selectableOptions && props.selectableOptions.map((opt) => <Option key={opt.id} value={opt.id}>{opt.name}</Option>)}
</Select>
</Form.Item>
NB: Use the props directly rather than the fieldValue for the options

Resources