Reputation: 151
I want my form to submit price data as an array format, currently, my form has a map, look like
{data.Type &&
<div>
{data.Type.map((datamapped)=>
<div key={datamapped._id}>
<p>{datamapped.TypeName}</p>
<Form.Item>
{getFieldDecorator(`price.${datamapped._id}.basePrice`)(
<Input placeholder="Base Price"/>,
)}
{getFieldDecorator(`price.${datamapped._id}.higherPrice`)(
<Input placeholder="Higher Price"/>,
)}
</div>
)}
</div>
}
Here I mapping my Type here and included, basePrice and higherPrice fields
result is :
price:
{
'5dc2913cf9e2372b11db4252': { basePrice: '0', higherPrice: '0' },
'5dc2a109f9e2372b11db4253': { basePrice: '0', higherPrice: '0' }
},
I want the above result as an array format how to do it?
Upvotes: 5
Views: 18109
Reputation: 839
Another way to get values as an array is to provide an array as FormItem name attribute like this:
<FormItem name={['wrapperName', index, 'propertyName']}>
<Input/>,
</FormItem>
Upvotes: 9
Reputation: 153
const MyForm = ({ form = {} }) => {
const { getFieldValue, getFieldDecorator } = form;
const [defaultData, setDefaultData] = useState({});
const add = ()=>{
// 🚩
defaultData.price.push({basePrice: 'zz',
higherPrice: 'hzz',key: new Date().getTime()})
}
return (
<Form>
<Form.Item>
{Array.isArray(defaultData.price) && // 🚩
defaultData.price.map((datamapped, index) => {
return (
<div key={datamapped.id||datamapped.key}>
{getFieldDecorator(`price[${index}].basePrice`, { // 🚩
initialValue: datamapped.basePrice,
})(<Input placeholder="Base Price" />)}
{getFieldDecorator(`price[${index}].higherPrice`, {
initialValue: datamapped.higherPrice,
})(<Input placeholder="Higher Price" />)}
</div>
);
})}
</Form.Item>
<Button onClick={add}> + </Button>
</Form>
);
};
export default Form.create()(MyForm);
|-- price array[object]
|-- basePrice string
|-- higherPrice string
const [defaultData, setDefaultData] = useState({})
setDefaultData({
price: [
{
basePrice: 'xx',
higherPrice: 'hxx',
},
{
basePrice: 'yy',
higherPrice: 'hyy',
},
],
});
⚠️ setFieldsValue only works in the first calling
Upvotes: 0
Reputation: 910
You can try this:
var json = {
price: {
"5dc2913cf9e2372b11db4252": { basePrice: "0", higherPrice: "0" },
"5dc2a109f9e2372b11db4253": { basePrice: "0", higherPrice: "0" }
}
};
json.price = Object.entries(json.price);
console.log(json);
Upvotes: 0
Reputation: 7054
Try change datamapped._id
to [index]
{data.Type &&
<div>
{data.Type.map((datamapped, index)=>
<div key={datamapped._id}>
<p>{datamapped.TypeName}</p>
<Form.Item>
{getFieldDecorator(`price[${index}].basePrice`)(
<Input placeholder="Base Price"/>,
)}
{getFieldDecorator(`price[${index}].higherPrice`)(
<Input placeholder="Higher Price"/>,
)}
</div>
)}
</div>
}
Upvotes: 4