Reputation: 557
I have a form in which there is a multi select dropdown antd component . On change of the select all option , I need to select all the options available with max of 5 tags .
Please find the link of my code in codesandbox here https://codesandbox.io/s/summer-wind-1swto
Max tag of 5 is sepecified with handleSelectAll function is called on select of options
<Form.Item label= 'Column Names'>
{getFieldDecorator(`columnNames`, {
validateTrigger: ['onChange', 'onBlur'],
rules: [
{
required: true,
message: "Please input the Column Names!",
},
],
})(
<Select
mode="multiple"
placeholder="Please select Columns"
maxTagCount={5}
onChange={this.handleSelectAll}
>
<Option key="all" value="all">---SELECT ALL---</Option>
{children}
</Select>
)}
</Form.Item>
Expected:
On select all is clicked all the options to be selected
On unchecking it all options to be removed
Upvotes: 7
Views: 36456
Reputation: 61
I prefer using dropdownRender
aproach instead of getFieldDecorator
const handleSelectAllClick = () => {
form.setFieldValue(
"items",
myOptions.map(({value}) => value)
);
form.validateFields(["items"]);
}
<Form.Item name="items">
<Select
mode="multiple"
allowClear
showArrow
maxTagCount="responsive"
options={myOptions}
dropdownRender={(menu) => (
<>
{menu}
<Divider />
<div>
<Button
type="text"
className="w-100"
shape="round"
onClick={handleSelectAllClick}
>
Select All
</Button>
</div>
</>
)}
/>
</Form.Item>
Upvotes: 1
Reputation: 1
On 4.x version.
I think you should set value on form.setFieldsValue({nameOfFormItem: valueSelected
}}
Upvotes: 0
Reputation: 798
In your case, setFieldsValue
is not working. But you can use getValueFromEvent
.
handleSelectAll = (value) => {
if (value && value.length && value.includes("all")) {
if (value.length === all.length + 1) {
return [];
}
return [...all];
}
return value;
}
<Form.Item label='Column Names'>
{getFieldDecorator(`columnNames`, {
validateTrigger: ['onChange', 'onBlur'],
getValueFromEvent: this.handleSelectAll,
rules: [
{
required: true,
message: "Please input the Column Names!",
},
],
})(
<Select
mode="multiple"
placeholder="Please select Columns"
maxTagCount={5}
onChange={this.handleSelectAll}
>
<Option key="all" value="all">---SELECT ALL---</Option>
{children}
</Select>
)}
</Form.Item>
This will work. handleSelectAll
event returns the value assigned using getValueFromEvent
and initialized the select component.
Upvotes: 8