Antd : Get form data - reactjs

As a part I'm working on, I need to take the data from a form when the user presses enter and use that data in a Modal. But the data doesn't seem to get extracted from the form. Here is my code :
const showModal = (info: any) => {
if(info.keyCode===13){
setIsModalOpen(true);
setData(info.form.note); // Some issue in this line
}
};
<SearchResults openModal={isModalOpen} message={data}/>
<Form name="control-ref" onKeyUp={showModal}>
<Form.Item name="note" id="note" rules={[{ required: true }]}>
<InputField
variant="search"
placeholder="Search"
addonAfter={selectAfter}
className="search-field"
/>
</Form.Item>
</Form>
I just need to find how to access form data. Please help

Related

How to get values of modal form antd

I'm trying to create a form inside modal using react class component and antd, but i couldn't find a way to get the data submited in the form. i tried to console the event of the onOk in antd modal but i same no data.
i also found an example but it was with function component and hooks Form.useForm()
here is the simple if anyone can help : Simple
any hint will be helpful thanks.
The solution is to hide the footer of the modal and add submit for the form exemple :
<Modal
title={this.props.formTitle}
visible={this.state.modalVisible}
confirmLoading={this.state.confirmLoading}
onCancel={this.handleCancel}
footer={[]}//this to hide the default inputs of the modal
>
<Form
layout="vertical"
name="form_in_modal"
initialValues={{
modifier: 'public',
}}
onFinish={this.handleOk}>
<Form.Item
name="title"
label="Title"
rules={[
{
required: true,
message: 'Please input the title of collection!',
},
]}>
<Input />
</Form.Item>
<Form.Item name="description" label="Description">
<Input type="textarea" />
</Form.Item>
<Form.Item name="modifier" className="collection-create-form_last-form-item">
<Radio.Group>
<Radio value="public">Public</Radio>
<Radio value="private">Private</Radio>
</Radio.Group>
//this is the submit of the form
<Button key="submit" type="primary" loading={this.state.confirmLoading} htmlType="submit">
submit
</Button>
</Form.Item>
</Form>
</Modal>
I tried this out myself with limited TS(JS) knowledge using Antd & React framework.
The steps are as follow.
construct an object e.g:
let obj1 = {
variableA : "",
variableB : ""
}
In your form body get the value using
<Form.Item ... onChange={(event)=>obj1.variableA=event.target.value}/>
In this case, the event keyword will return the final input value to instances (e.g variableA) within obj1 with given input from different form, which you can operate on after the form submission finish in a quasi-java style.
You can test it by creating alert(obj1.variableA) or console.log function to see if that's the desired value, in my case it works well with string and numeric input.
As I am not doing front end, so I might make mistakes and do feel free to point it out.

Antd validation on Input with hasFeedback and validateStatus

I was trying validation of input field with hasFeedback, validateStatus of ANT Design. If I set validateStatus = 'error' for now which I actually would set with state, I was able to get alert from onFinish function. Am I missing something ?? I read documents and found onFinish will only trigger when validation has passed.
I want to validate that with my own validation rules and states.
function onfinish(){
alert('hi')
}
<Form
form={form}
onFinish={onfinish}
>
<Form.Item
label="Mobile Number"
validateStatus='error'
hasFeedback
name="mobileNumber"
>
<Input id='abc'/>'
</Form.Item>
</Form>

React-Final-Form delays in taking input with render props in Field

I am currently working on a react project. I am using react-final-form for fetching the data in the form. As I am using the material UI component to create the form I am creating the form somewhat like this.
Code
<Form
onSubmit={onSubmit}
validate={validate}
render={({ handleSubmit, values }) => (
<form onSubmit={handleSubmit}>
<FormControl variant="outlined" className={classes.formControl} key={fieldKey}>
<Field
name={field.fieldName}
render={({ input }) => (
<TextField
{...input}
className={classes.textField}
variant="outlined"
label={props.field.label}
placeholder={props.field.description}
required={props.field.isMandatory}
InputLabelProps={{
shrink: true,
}}
/>
)}
type="text"
/>
</FormControl>
</form>
)}
/>
Now as soon as I remove the input props from the render props it is working fine. but with the input props, it delays in taking input. Without input props, I could not fetch the value from the form.
Is there any way to resolve this time delay?
Thanks in advance.
If you want a simple field. Maybe you can pass on only essential props.
<TextField
name={input.name}
value={input.value}
onChange={input.onChange}
/>
The solution to this is subscriptions.
The form is initially rendered on every action, react-final-form allows to handle subscription,
<Form subscription={{handeleSubmit: true}} ...> </Form>
We can do somewhat like this
There is a video link for this. Video
Hope you find this helpful 😉

Ant.design does not detect custom input component in Form.Item React

So, the main problem is, that antd form does not detect my custom input based on antd standard input:
There is a piece of form code (AddProduct):
<Form.Item
className="m-t-10"
name="price"
rules={[
{
required: true,
message: `${t('FORM.ERR.SHOP.PRICE')}`,
},
]}
>
<CurrencyInput size="small" placeholder={t('FORM.SHOP.PRICE_VAT')} name="price" />
</Form.Item>
There is my custom input (CurrencyInput):
return (
<Input size={props.size} placeholder={props.placeholder} name={props.name} type="number" prefix={settings[6].value} />
)
The problem is when I try to submit the form it does not detect currency input, throws err that this field is required. Any ideas are it possible to implement custom input, basically, it's more HOC than custom input
You need to pass to your custom component all props, because Form.Item pass to there onChange and value props
function CustomInput({size, placehodler, name, ...restProps}) {
return (
<Input size={size} placeholder={placeholder} name={name}
type="number" prefix={settings[6].value} {...restProps} />
)
}

How to serialize a form where name is different than data structure

How can I serialize a form whose data structute is different to it's name.
For example, I have following form, which is getting numberofItems from inventory object and displaying in a TextArea.
<Form
enableReinitialize={true}
initialValues={{
numberofItems: inventories.numberofItems
}}
onSubmit={handleSubmit}
>
<FormItem
name={'numberofItems'}
label={'Current Stock'}
maxLength={32000}
>
{inputProps => <TextArea {...inputProps} />}
</FormItem>
</Form>
This works fine when rendering the form. But when I try to post the form, the expected property is null. Because, the service expects inventories.numberofItems where as I am sending numberofItems , as per it's name.
I can avoid this by doing passing the object to form and extracting each field to control.
<Form
enableReinitialize={true}
initialValues={{
inventories: inventories
}}
onSubmit={handleSubmit}
>
<FormItem
name={'inventories.numberofItems'}
label={'Current Stock'}
maxLength={32000}
>
{inputProps => <TextArea {...inputProps} />}
</FormItem>
</Form>
But is there a way I can serialize a control, with a different key from it's name.
In my case, I want to serialize the form with inventories.numberofItems while keeping the name of the control as numberofItems.
<FormItem
name={'numberofItems'}
label={'Current Stock'}
maxLength={32000}
>
{inputProps => <TextArea {...inputProps} />}
</FormItem>
What you can do in order to successfully submit the form (I don't know if it fits your needs though, this is what I do in similar cases in my code where I have JAX-RS backend which cannot map to unknown properties of object) is set the required property and delete the one that cannot be submitted.
function handleSubmit(myFormObject) {
myFormObject.inventories = {numberofItems: myFormObject.numberofItems}
delete myFormObject.numberofItems
.
.
.
}
redux-form supports such cases though. You can define a Field with property name being a "compound" one and it will properly map to your form object being submitted.
Check this sample codesandbox
<Field name="test.notes" component="textarea" />

Resources