23

I am having a hard time with antd's form. I have this select field in this form and I want to get the value from it onChange but somehow not getting it to work properly.

say this is the item for which I want the values

<FormItem
  {...formItemLayout}
  label={fieldLabels.qcategoryid}
  validateStatus={categoryError ? "error" : ""}
  help={categoryError || ""}
>
  {getFieldDecorator("qcategoryid", {
    rules: [{ required: true, message: "Please select Category!" }],
    onChange: this.handleCategoryChange
  })(<Select>{categoryOptions}</Select>)}
</FormItem>

this is the categoryOptions

if (this.props.categories) {
  categoryOptions = this.props.categories.map(item => (
    <Select.Option
      key={item.categoryid}
      value={item.categoryid}
      name={item.categoryname}
    >
      {item.categoryname}
    </Select.Option>
  ));
}

I want both the name of the category and the id so I created a handleCategoryChange which gets called onChange and I am able to get the fields I want.

But, it seems that now, I have to click twice on the field to properly select it. If I click it just once then it does show up in the console. but the field on the form still remains empty. when I click it again, then the field shows up in the form too.

So, what am I doing wrong here. Ah,yes! Here's the handleCategoryChange function

handleCategoryChange = (value, e) => {
  console.log("value is : ", value);
  console.log("e : ", e);
  this.props.form.setFieldsValue({ qcategoryid: value });
  this.setState({
    categorySelected: value,
    categoryname: e.props.name
  });
};

Just to make myself clear. I need those values before I click submit. not on submit.

faraz
  • 2,603
  • 12
  • 39
  • 61

6 Answers6

12

maybe this will help Ant Design form API as of 22nd of May 2022

This was added in v4.20

const Demo = () => {
  const [form] = Form.useForm();
  const userName = Form.useWatch('username', form);

  const { data: options } = useSWR(`/api/user/${userName}`, fetcher);

  return (
    <Form form={form}>
      <Form.Item name="username">
        <AutoComplete options={options} />
      </Form.Item>
    </Form>
  );
};
Mnengwa
  • 217
  • 4
  • 10
3

Try this:

<FormItem
  {...formItemLayout}
  label={fieldLabels.qcategoryid}
  validateStatus={categoryError ? "error" : ""}
  help={categoryError || ""}
>
  {getFieldDecorator("qcategoryid", {
    rules: [{ required: true, message: "Please select Category!" }]
  })(<Select onChange={this.handleCategoryChange}>{categoryOptions}</Select>)}
</FormItem>

And on the handleCategoryChange function

handleCategoryChange = (value, e) => {
  this.setState({
    categorySelected: value,
    categoryname: e.props.name
  });
};

Basically, changing the onChange from the getFieldDecorator helper to the Select, so it doesn't mess with antd's natural behavior, but gets the value and change on state

I've based this answer on the code to the registration form on their website. Specifically, the handleWebsiteChange function

https://ant.design/components/form/#components-form-demo-register

iagowp
  • 2,428
  • 1
  • 21
  • 32
  • A few issues here, from the documentation of Form.Item: - You shouldn't use onChange on each form control to collect data(use onValuesChange of Form), but you can still listen to onChange. - You cannot set value for each form control via value or defaultValue prop, you should set default value with initialValues of Form. Note that initialValues cannot be updated by setState dynamically, you should use setFieldsValue in that situation. - You shouldn't call setState manually, please use form.setFieldsValue to change value programmatically. https://ant.design/components/form/#Form.Item – lacy Feb 10 '22 at 21:49
  • @lacy this post is from 2018, so it's possibly about antd v3 or even v2. I suppose they've changed how they do some stuff in the meanwhile and improved their documentation. Maybe you could write an updated answer if that question is still a relevant problem in current antd versions? – iagowp Feb 11 '22 at 23:10
3

I realize this is super late, but I think this might be what OP was looking for:

https://github.com/react-component/form/blob/3b9959b57ab30b41d8890ff30c79a7e7c383cad3/examples/server-validate.js#L74-L79

To set fields on a form dynamically, e.g. in a child via a callback, you could use

    this.props.form.setFields({
      user: {
        value: values.user,
        errors: [new Error('forbid ha')],
      },
    }); 

in a parent defined handleSelect method you called from the child on a selected value. you can alternatively use setFieldsValue if you dont want to pass an error field

mburke05
  • 1,371
  • 2
  • 25
  • 38
2
I have made a helper function to solve this problem, you have to pass the field 
name you want to take out from the form and the form object.

const getFieldValue = (fieldName,form) => {
   return Form.useWatch(fieldName,form);
}

console.log(getFieldValue("username"))

in above example I had to console updated username value.

demo

0

Putting this out there for anyone who runs into this issue in the future. I ran into a bug in the antd Select form item such that it returns undefined if nothing changed, and not the values stored (by load or default) in the form. Luckily, there's a straightforward and easy workaround: implement onChange with an object array variable to store the values.

let selectValues = [{label: 'default', value: 'default'}]

<Select onChange={vals=>{selectValues=vals}} ... />

now selectValues will store the form select values. Pretty simple solution but hopefully it helps

For non-Select form items, Mnengwa's solution above worked for me

liamhp
  • 111
  • 1
  • 7
-3

A quick response, and hopefully a quick solution. Rather than using onChange you may want to use onSelect/onDeselect handlers, per the documentation (https://ant.design/components/select/):

<Select onSelect={handleCategoryChange} .../>

I have found also that SELECT and other input components, due to their custom html nature operate differently, and so in my forms, I have often created them as dummy fields that are using to alter text/hidden inputs in order to achieve the desired behaviours in complex forms.

Either I am doing something wrong, or the ANT way is mildly annoying.

Hope this helps.

Vincro
  • 250
  • 1
  • 4
  • no. this way only works if you are not using it inside form. but when you are using it inside form, then this doesnt work. – faraz Jul 20 '18 at 01:10
  • What precludes you from using it inside a form? And would putting it in a form give you the desired effect? – Vincro Jul 20 '18 at 07:56
  • it doesnt work like this in a form. that's what I am saying. it behaves differently inside form – faraz Jul 20 '18 at 08:01