Я использую formik ArrayField
для своей формы.Логика формы следующая:
initialValues={{ name: '', group: false, users: [], channels: [] }}
channels: []
- это массив объектов, подобный следующему: channels: [{name: "", users: []}]
С моим текущим кодом это просто отлично работает, но есть одна проблема.Например, если в моем users: []
есть следующие значения:
[{key: '1', label: "John doe"}, {key: '2', label: 'Alex Andrew'}]
, а в моем channels: [ users: [{key: '1', label: "John doe"}, {key: '2', label: 'Alex Andrew'}] ]
проблем нет.Пользователи канала содержат только элементы из глобального массива пользователей, но, например, если элемент удаляется из глобального users[]
, и этот удаленный элемент присутствует в моем канале: [users: [] ]
этот элемент должен быть удален.
пример:
users: [{key: '1', label: "John doe"}]
channels: [ users: [{key: '1', label: "John doe"}, {key: '2', label: 'Alex Andrew'}]
{key: '2', label: 'Alex Andrew'}
элемент должен быть удален из массива каналов
Как это сделать?
Код:
class CreateChannelGroup extends Component<CreateChannelGroupProps, CreateChannelGroupState> {
render() {
const { onShowModal, showModal, getAllWorkspaceUsersStatus, users } = this.props;
return (
<div>
<Formik
initialValues={{ name: '', group: false, users: [], channels: [] }}
// validationSchema={CreateWorkspaceSchema}
onSubmit={(values: FormikValues) => {
console.log(values)
}}
>
{({
values,
errors,
touched,
handleChange,
handleSubmit,
setFieldValue,
}) =>
<Modal
title="Create a channel or group"
visible={showModal}
onOk={handleSubmit}
okButtonProps={{ htmlType: "submit" }}
onCancel={onShowModal}
okText='Create'
>
<Spin spinning={getAllWorkspaceUsersStatus === ProgressStatus.InProgress}>
<Form onSubmit={handleSubmit}>
<div style={{ margin: "10px 0px" }}>
<Input
placeholder="name"
type="text"
name="name"
onChange={handleChange}
value={values.name}
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
suffix={
<Tooltip title="This name will be used a group channel name">
<Icon type="info-circle" style={{ color: 'rgba(0,0,0,.45)' }} />
</Tooltip>
}
/>
</div>
<div style={{ margin: "10px 0px" }}>
<Select
mode="multiple"
labelInValue
value={values.users}
placeholder="User email"
onChange={(value, option: any) => {
let values = value.map((val: any, index: number) => ({ key: option[index].key, label: val.label }))
setFieldValue(`users`, values)
}}
style={{ width: '100%' }}
>
{users && users.length ? users.map(user => (
<Option key={user.id}>{user.user.firstName + ' ' + user.user.lastName}</Option>
)) : null}
</Select>
</div>
<div style={{ margin: "10px 0px" }}>
<Checkbox onChange={handleChange} name="group" value={values.group}>This is a channel group</Checkbox>
</div>
<FieldArray
name="channels"
render={arrayHelpers => (
<div>
<Form.Item>
{values.channels && values.channels.length >= 1 ? (
values.channels.map((channel: any, index) => (
<div key={index} style={{ padding: "10px", border: "1px solid #e8e8e8", borderRadius: "2px", margin: "10px 0px" }}>
<div style={{ display: "flex", justifyContent: "flex-end" }}>
<Icon type="delete" onClick={() => arrayHelpers.remove(index)} style={{ color: 'rgba(0,0,0,.45)' }} />
</div>
<Input
placeholder="name"
type="text"
name={`channels[${index}].name`}
onChange={handleChange}
value={channel.name}
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
suffix={
<Tooltip title="This name will be used a group channel name">
<Icon type="info-circle" style={{ color: 'rgba(0,0,0,.45)' }} />
</Tooltip>
}
/>
<Select
mode="multiple"
labelInValue
value={channel.users}
placeholder="User email"
notFoundContent={null}
onChange={(value, option: any) => {
let values = value.map((val: any, index: number) => ({ key: option[index].key, label: val.label }))
setFieldValue(`channels[${index}].users`, values)
}}
style={{ width: '100%' }}
>
{values.users && values.users.length ? values.users.map((user: any) => (
<Option key={user.key} value={user.label}>{user.label}</Option>
)) : null}
</Select>
</div>
))
) : null}
{values.group ? <Button size="small" onClick={() => arrayHelpers.push({ name: '', users: [] })}> Add a channel </Button> : null}
</Form.Item>
</div>
)}
/>
</Form>
</Spin>
</Modal>
}
</Formik>
</div>
);
}
}
export default CreateChannelGroup;