Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setFieldValue and pass the value as props between components

I'm trying to use ant design forms in my sample registration form, when i'm trying to use setFieldsValue it throws error as "Cannot use setFieldsValue unless getFieldDecorator is used". But I had already used getFieldDecorator in my code.Here is a sample of my code.

handleChange = (e) => {
  const fname = e.target.name;
  const fvalue = e.target.value;
  this.props.setFieldsValue({
    fname: fvalue
  });
}
render(){
  const { getFieldDecorator } = this.props.form
  return (
    <Row gutter={4}>
      <Col className="reg-personal-details-grid-column" span={24}>
        <FormItem {...formItemLayout} label="First Name">
          {getFieldDecorator("firstName", {
            rules: [
              {
                required: true
              }
            ]
          })(
            <Input
              placeholder="First Name"
              required
              name="firstName"
              onChange={this.handleChange}
            />
            )}
        </FormItem>
      </Col>
    </Row>
  )
}
like image 725
Shibu Avatar asked Mar 07 '23 09:03

Shibu


2 Answers

fname is not defined in getFieldDecorator.

You should do this:

handleChange = (e) => {
  const fname = e.target.name;
  const fvalue = e.target.value;
  this.props.form.setFieldsValue({
    [fname]: fvalue
  });
}
like image 165
Vicky Avatar answered May 09 '23 11:05

Vicky


You can create your own function to do this:

export const setFieldValue = (
    form: FormInstance,
    name: NamePath,
    value: string
): void => {
    if (form && form.getFieldValue(name)) {
        const fixname: string[] = [];
        if (typeof name == 'object') {
            name.forEach((node: string) => {
                fixname.push(node);
            });
        } else {
            fixname.push(String(name));
        }
        let fieldsValue: unknown;
        fixname.reverse().forEach((node: string) => {
            fieldsValue = {
                [String(node)]: fieldsValue != undefined ? fieldsValue : value,
            };
        });
        form.setFieldsValue(fieldsValue);
    }
};

and you can use like that

setFieldValue(form, 'phone', '1111111111');

or

setFieldValue(form, ['phones', 'mobile'], '2222222222');
like image 30
Rodrigo Brandão Avatar answered May 09 '23 09:05

Rodrigo Brandão