简体   繁体   中英

How can I set data on a Select component with Ant Design?

I've been using Ant Design with Javascript to build a table in which you can edit a row information just by clicking an edit button and the row will turn into "editing mode", this allows you to visualize the information that was already there but now is editable. I was able to accomplish that will every kind of input except with the Select componen. As you can see in the next screenshot (I framed the fields that are Select Components): fields in which I used Select Component

Now, when I click the "Edit" button I retrieve all data except for the ones that use the Select Component as you can see in the next screenshot : Select Component doesn't shows the existing data

The next block of code is the one that I've been using to set the data in editing mode:

const edit = (record) => {

        form.setFieldsValue({
            ...record
        });

        setEditingKey(record._id);
    };

This is the code for the table:

return (
        <Form form={form} component={false}>
            <Space align="start" wrap={true}>
                <Button
                    onClick={handleAdd}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                    size='large'
                >
                    Añadir Usuario
                </Button>
                <AutoComplete
                    dropdownMatchSelectWidth={252}
                    style={{
                        width: 300
                    }}
                >
                    <Input.Search size='large'
                        placeholder="Buscar..."
                        enterButton
                        onSearch={(value) => {
                            setSearchedText(value);
                        }}
                    />
                </AutoComplete>

            </Space>
            <Table
                locale={{
                    triggerDesc: 'Ordenar descendiente',
                    triggerAsc: 'Ordenar ascendiente',
                    cancelSort: 'Cancelar ordenamiento'
                }}
                rowKey={record => record._id}
                components={{
                    body: {
                        cell: EditableCell,
                    },
                }}
                bordered
                dataSource={data}
                columns={mergedColumns}
                rowClassName="editable-row"
                pagination={{
                    onChange: cancel,
                    pageSize: 10
                }}
                scroll={{ x: 2150 }}
            />
        </Form>
    );

And this is the "EditableCell" that appears when the user clicks on the edit button:

const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = dataIndex === "password" ? <Input.Password /> : <Input />;
    return (
        <td {...restProps}>
            {editing ? (
                <>
                    {(title === "Sexo*" || title === "Discapacidad" || title === "Rol*" || title === "Tutor*") ? (
                        <Select
                            mode={(title === "Discapacidad") ? "multiple" : ""}
                            allowClear={(title === "Discapacidad") ? true : false}
                            style={{
                                width: '100%',
                            }}
                            placeholder="Seleccione una opción"
                            onChange={(val) => {
                                const col = selectedValues.find(column => column.title === title);
                                if (title === "Discapacidad") {
                                    let newArray = [...val]
                                    if (col.values.includes([...val])) {
                                        newArray = newArray.filter(disa => disa !== [...val])
                                    }
                                    col["values"] = newArray;
                                } else if (title === "Sexo*" || title === "Rol*" || title === "Tutor*") {
                                    col["values"] = val;

                                }
                            }}
                        >
                            {options(title)}
                        </Select>
                    ) : (
                        <Form.Item
                            name={dataIndex}
                            style={{
                                margin: 0,
                            }}
                            rules={[
                                {
                                    required: (title === 'Fundación') ? false : true,
                                    message: `¡Introduzca un ${title} válido!`,
                                    pattern: rules(dataIndex),
                                },
                            ]}
                        >
                            {inputNode}
                        </Form.Item>
                    )}
                </>
            ) : (
                children
            )}
        </td>
    );
};

So if anyone knows how to set the data that was already saved so the user can see it when it's editing, I'd be grateful.

You are using the form.setFieldsValue method, but as I can see, your Select is just not wrapped by Form.Item element to be part of the form instance.

So you can wrap your Select by Form.Item as you do for others inputNode or rewrite your conditional logic to add select as inputNode inside existing Form.Item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM