Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a questionnaire type form using Ant Design?

Tags:

reactjs

antd

Ant Design provides a Dynamic Form Item, by using that, I can add and remove multiple fields. But now I want do nesting in that, i.e., I want to create a questionnaire like form in which I want to add multiple questions and their respective answers.

Currently, when I am adding questions, its working correct but when I am adding answer to one question, its also adding to the all questions.

The functions of adding and removing questions and answers are as given below:

remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k)
    });
  };

  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    const nextKeys = keys.concat(uuid);
    uuid++;
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys
    });
  };

  remove1 = k1 => {
    const { form } = this.props;
    // can use data-binding to get
    const keys1 = form.getFieldValue("keys1");
    // We need at least one passenger
    if (keys1.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys1.filter(key1 => key1 !== k1)
    });
  };

  add1 = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys1 = form.getFieldValue("keys1");
    const nextKeys1 = keys1.concat(uuid1);
    uuid1++;
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys1: nextKeys1
    });
  };

I have created a demo on codesandbox.io.

like image 383
Triyugi Narayan Mani Avatar asked Dec 05 '25 02:12

Triyugi Narayan Mani


1 Answers

The problem is not in the functions but in getFieldDecorator:

<FormItem>
     {getFieldDecorator(`answer[${k}]`, {
         validate: [
         ...
         ]
         })(<Input type="" placeholder=" Enter Answer" />)

You submit the same input value for all inputs.

Without the decorator it works fine and you can put validation to your custom function and call it

 <FormItem>
     <Input 
         type="" 
         placeholder=" Enter Answer" 
         // value={this.state.answer}
         // onChange={e => this.handleChange(e)} 
      />
 </FormItem>

UPD: Added the full code - Sandbox try

like image 192
Roman Haivaronski Avatar answered Dec 07 '25 18:12

Roman Haivaronski