1

I have a dynamic form in Ant Design where I can:

  • set the price and the quantity in some inputs.
  • create new rows

I was able to access all the values from the rows after submiting with this piece of code:

  const onFinish = values => {
    console.log("Received values of form:", values);
  };

But I would like to access each value from the inputs, get the total (price * quantity) and set it the total input.

enter image description here

I saw a solution in basic React from this question Calculating quantity and price total in react. That answer shows that you need use state and use the onChange event and work from there, but I don't really know how to translate this answer because I don't understand how to access the state from each row in Ant Design.

You can see my code right here: https://codesandbox.io/s/stupefied-hawking-pcr7k?file=/index.js:260-348

Any help would be appreciated

Javier Cárdenas
  • 3,935
  • 4
  • 25
  • 35

1 Answers1

1

You can calculate derived values by taking advantage of the onValuesChange event handler on the Form component, and the form instance methods provided by the Form.useForm hook.

Please see sandbox example:

https://codesandbox.io/s/antdesign-calculating-a-derived-value-using-dynamic-form-hgyzh?file=/index.js:229-1020

const ItemForm = () => {
  const [form] = Form.useForm()
  const onFinish = values => {
    console.log('Received values of form:', values)
  }

  const handleTotal = (_, values) => {
    const rowsCopy = [...values.rows]
    values.rows.forEach((fieldGroup, index) => {
      if (fieldGroup && fieldGroup.quantity && fieldGroup.price) {
        fieldGroup.total = fieldGroup.quantity * fieldGroup.price
        rowsCopy.splice(index, 1, fieldGroup)
        console.log('fieldGroup', fieldGroup)
        console.log('rowsCopy', rowsCopy)
        form.setFieldsValue({ rows: rowsCopy })
      }
    })
  }

  return (
    <Form
      name="dynamic_form_nest_item"
      form={form}
      onFinish={onFinish}
      onValuesChange={handleTotal}
      autoComplete="off"
      size="small"
    >
Cesar N Mejia Leiva
  • 1,611
  • 1
  • 12
  • 18
  • thanks, what is the first parameter of handleTotal `_`? and why do you need to copy the rows in this part `rowsCopy.splice(index, 1, fieldGroup)`? – Javier Cárdenas Jun 06 '20 at 20:06
  • 1
    The first parameter is `changedValues`, basically only the last value that was changed on the form. As for `rowsCopy` that is just for convenience, the splice step is replacing the edited form group {count: XX, price: XX, total: undefined} with {count: XX, price: XX, total: CALCULATED_TOTAL}. – Cesar N Mejia Leiva Jun 06 '20 at 20:10