te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - How to create dynamic form input fields in React with ANTd - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create dynamic form input fields in React with ANTd - Stack Overflow

programmeradmin4浏览0评论

Codesandbox link: =/src/App.js

I have not been able to find much information on this topic. The following is what I want to achieve:

I want the user to be able to edit some details of a purchase order that already exists in the database, then resubmit the purchase order with a form. The details of the original purchase order should be displayed in the form input fields, and the user can change them directly via those field and then submit.

I am not savvy with web development so please bear with me.

I want the final form object to look like this:

{
    po_number:"123abc",
    carrier:"Fastway",
    items: [{
                item_code:"dnh75n",
                quantity:"10",
                special_requirements:"Add picture of happy dog"
            },
            {
                item_code:"456def",
                quantity:"4",
                special_requirements:"Do not include lids"
            }
        ]
}

The number of form input fields generated will be based off how many items are in the purchase order. I have created a simple React ponent below to demonstrate what I am trying to do. Or just checkout out the code sandbox link above. Any help would be appreciated. I can't even find information on how to group ANTd form items to create the array of items in the purchase order. I've seen plenty of dynamic form examples on their website but I want to create the form based on the preexisting items in the purchase order, not add fields with user input.

import { Form, Input, Button } from 'antd';

//This is the order that already exists
const order = {
    po_number:"123abc",
    carrier:"Fastway",
    items: [{
                item_code:"dnh75n",
                quantity:"10",
                special_requirements:"Add picture of happy dog"
            },
            {
                item_code:"456def",
                quantity:"4",
                special_requirements:"Do not include lids"
            }
        ]
};


const GroupForm = () => {

    const onFinish = values => {
        console.log(values);
    }
    

    //Create form fields based off how many items are in the order
    const itemInputs = order.items.map(item => {
        return (
            <div>
                <b>Item{" " + item.item_code}</b>
                <Form.Item name={item.item_code + "_quantity"} label="quantity">
                    <Input defaultValue={item.quantity} style={{width: "500px"}} />
                </Form.Item>

                <Form.Item name={item.item_code + "_requirements"} label="speacial requirements">
                    <Input defaultValue={item.special_requirements}  style={{width: "500px"}} />
                </Form.Item>
            </div>
        );
    });

    return(
        <div>
            <Form onFinish={onFinish}>
                <b>{"Order " + order.po_number}</b>
                
                <Form.Item name="carrier" label="carrier">
                    <Input defaultValue={order.carrier} style={{width: "500px"}} />
                </Form.Item>

                <b>Order Items</b>

                {itemInputs}

                <Form.Item>
                    <Button type="primary" htmlType="submit"> Change Details </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default GroupForm;

Codesandbox link: https://codesandbox.io/s/passionate-sanderson-1m8nv?file=/src/App.js

I have not been able to find much information on this topic. The following is what I want to achieve:

I want the user to be able to edit some details of a purchase order that already exists in the database, then resubmit the purchase order with a form. The details of the original purchase order should be displayed in the form input fields, and the user can change them directly via those field and then submit.

I am not savvy with web development so please bear with me.

I want the final form object to look like this:

{
    po_number:"123abc",
    carrier:"Fastway",
    items: [{
                item_code:"dnh75n",
                quantity:"10",
                special_requirements:"Add picture of happy dog"
            },
            {
                item_code:"456def",
                quantity:"4",
                special_requirements:"Do not include lids"
            }
        ]
}

The number of form input fields generated will be based off how many items are in the purchase order. I have created a simple React ponent below to demonstrate what I am trying to do. Or just checkout out the code sandbox link above. Any help would be appreciated. I can't even find information on how to group ANTd form items to create the array of items in the purchase order. I've seen plenty of dynamic form examples on their website but I want to create the form based on the preexisting items in the purchase order, not add fields with user input.

import { Form, Input, Button } from 'antd';

//This is the order that already exists
const order = {
    po_number:"123abc",
    carrier:"Fastway",
    items: [{
                item_code:"dnh75n",
                quantity:"10",
                special_requirements:"Add picture of happy dog"
            },
            {
                item_code:"456def",
                quantity:"4",
                special_requirements:"Do not include lids"
            }
        ]
};


const GroupForm = () => {

    const onFinish = values => {
        console.log(values);
    }
    

    //Create form fields based off how many items are in the order
    const itemInputs = order.items.map(item => {
        return (
            <div>
                <b>Item{" " + item.item_code}</b>
                <Form.Item name={item.item_code + "_quantity"} label="quantity">
                    <Input defaultValue={item.quantity} style={{width: "500px"}} />
                </Form.Item>

                <Form.Item name={item.item_code + "_requirements"} label="speacial requirements">
                    <Input defaultValue={item.special_requirements}  style={{width: "500px"}} />
                </Form.Item>
            </div>
        );
    });

    return(
        <div>
            <Form onFinish={onFinish}>
                <b>{"Order " + order.po_number}</b>
                
                <Form.Item name="carrier" label="carrier">
                    <Input defaultValue={order.carrier} style={{width: "500px"}} />
                </Form.Item>

                <b>Order Items</b>

                {itemInputs}

                <Form.Item>
                    <Button type="primary" htmlType="submit"> Change Details </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default GroupForm;

Share Improve this question asked Jan 28, 2021 at 2:14 TomTom 2212 gold badges5 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

If you're using antd version 4.9.0+, you can take advantage of the initialValue property on the Form.List. This allows you set intial values on the form items of the array. Alternatively, you can set the initialValues property on the Form. Here's a minimum viable example using the former method.

import { Form, Input, Button, Space } from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import React from "react";

//Basic Idea
/* 
    I want the user to be able to edit some details of a purchase order that already exists in the database,
    then resubmit the order with a form.
    The details of the purchase order should be orginally displayed in the form input fields,
    and the user can change them directly via those fields. 
*/

//This is the order that already exists
const order = {
  po_number: "123abc",
  carrier: "Fastway",
  items: [
    {
      item_code: "dnh75n",
      quantity: "10",
      special_requirements: "Add picture of happy dog"
    },
    {
      item_code: "456def",
      quantity: "4",
      special_requirements: "Do not include lids"
    }
  ]
};

const itemInputs = order.items

const GroupForm = () => {
  const onFinish = (values) => {
    console.log(values);
  };

  /**
   * Edited: `const itemInputs = order.items` above
   */
  //Create form fields based off how many items are in the order
  // const itemInputs = order.items.map((item) => {
  //   return {
  //     item_code: item.item_code,
  //     quantity: item.quantity,
  //     special_requirements: item.special_requirements
  //   };
  // });

  return (
    <div>
      <Form onFinish={onFinish}>
        <b>{"Order " + order.po_number}</b>

        <Form.Item name="carrier" label="carrier" initialValue={order.carrier}>
          <Input style={{ width: "500px" }} />
        </Form.Item>
        <Form.Item
          name="po_number"
          label="PO number"
          initialValue={order.po_number}
          hidden
        >
          <Input />
        </Form.Item>

        <b>Order Items</b>

        <Form.List name="items" initialValue={itemInputs}>
          {(fields, { add, remove }) => (
            <>
              {fields.map((field) => (
                <Space
                  key={field.key}
                  style={{ display: "flex", marginBottom: 8 }}
                  align="baseline"
                >
                  <Form.Item
                    {...field}
                    name={[field.name, "item_code"]}
                    // no need anymore
                    // fieldKey={[field.fieldKey, "item_code"]}
                  >
                    <Input placeholder="Item Code" />
                  </Form.Item>
                  <Form.Item
                    {...field}
                    name={[field.name, "quantity"]}
                    // no need anymore
                    // fieldKey={[field.fieldKey, "quantity"]}
                  >
                    <Input placeholder="Quantity" />
                  </Form.Item>
                  <Form.Item
                    {...field}
                    name={[field.name, "special_requirements"]}
                    // no need anymore
                    // fieldKey={[field.fieldKey, "special_requirements"]}
                  >
                    <Input placeholder="Quantity" />
                  </Form.Item>
                  <MinusCircleOutlined onClick={() => remove(field.name)} />
                </Space>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={add}
                  block
                  icon={<PlusOutlined />}
                >
                  Add item
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            {" "}
            Change Details{" "}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default GroupForm;

// I want to submit a form object that looks like this. E.g.
// This is what 'onFinish' should display in the console
/*

{
    po_number:"123abc",
    carrier:"Fastway",
    items: [{
                item_code:"dnh75n",
                quantity:"10",
                special_requirements:"Add picture of happy dog"
            },
            {
                item_code:"456def",
                quantity:"4",
                special_requirements:"Do not include lids"
            }
        ]
}

*/

DEMO

Thanks to Scratch'N'Purr, I used your solution to further put the fields into an antd table.

First a short note: fieldKey={[field.fieldKey, "quantity"]} from the previous solution didn't work for me, but changing it to key={[field.key, "quantity"]}did the trick.

//define the columns for the table
const columns = [
    {
      title: "ITEM#",
      dataIndex: "item_code",
      key: "item_code",
      width: "12%",
      //use the field here to get all infos for the form
      render: (_, field) => (
        <Form.Item
          {...field}
          name={[field.name, "item_code"]}
          key={[field.key, "item_code"]}
          noStyle
        >
          <Input placeholder="ITEM#" />
        </Form.Item>
      ),
    },
    {
      title: "Quantity",
      dataIndex: "quantity",
      key: "quantity",
      render: (_, field) => (
        <Form.Item
          {...field}
          name={[field.name, "quantity"]}
          //@ts-ignore
          key={[field.key, "quantity"]}
          noStyle
        >
          <Input placeholder="Quantity" />
        </Form.Item>
      ),
}];

const GroupForm = () => {
  const onFinish = (values) => {
    console.log(values);
  };

  //Create form fields based off how many items are in the order
  const itemInputs = order.items.map((item) => {
    return {
      item_code: item.item_code,
      quantity: item.quantity,
      special_requirements: item.special_requirements,
    };
  });

  return (
    <div>
      <Form onFinish={onFinish}>
        <b>{"Order " + order.po_number}</b>
        <Form.Item name="carrier" label="carrier" initialValue={order.carrier}>
          <Input style={{ width: "500px" }} />
        </Form.Item>
        <Form.Item
          name="po_number"
          label="PO number"
          initialValue={order.po_number}
          hidden
        >
          <Input />
        </Form.Item>

        <b>Order Items</b>

        <Form.List name="items" initialValue={itemInputs}>
          {(fields, { add, remove }, { errors }) => (
            <>
              {/* This is where to put the table. As a data source i used the fields */}
              <Table dataSource={fields} columns={columns} pagination={false} />
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{ width: "60%" }}
                  icon={<PlusOutlined />}
                >
                  Add field
                </Button>
                <Form.ErrorList errors={errors} />
              </Form.Item>
            </>
          )}
        </Form.List>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            {" "}
            Change Details{" "}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};


发布评论

评论列表(0)

  1. 暂无评论