Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(select): add selectByValue prop to autopopulate an option #768

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docusaurus/docs/form/select/components/select.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,13 @@ For example, if the new value is `{ "payer": { "name": "Availity", "id": "1" } }
payerNameAndId: opt => `${opt.payer.id} - ${opt.payer.name}`,
}
```

### `selectByValue?: SelectByValue`

Allows the value passed to be automatically selected in the dropdown. If the options are strings, pass the `value` property as the value to match on. If the dropdown options are objects, pass a `key` and `value` property to match the unique option where the `option[key]` value is equal to `value`.

For example, to match an organization on the AvOrganizationSelect (the options are the entire organization object), you can match the `customerId` as the `key` to the `value` of `1234`

```js
selectByValue={{key: 'customerId', value: '1234'}}
```
26 changes: 26 additions & 0 deletions packages/select/src/ResourceSelect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { useRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import qs from 'qs';
import get from 'lodash/get';
import find from 'lodash/find';
import { useFormikContext } from 'formik';

import Select from './Select';
Expand All @@ -28,6 +29,7 @@ const ResourceSelect = ({
additionalPostGetArgs,
pageAll,
pageAllSearchBy,
selectByValue,
...rest
}) => {
const { setFieldValue } = useFormikContext();
Expand All @@ -37,6 +39,13 @@ const ResourceSelect = ({
const [previousOptions, setPreviousOptions] = useState([]);
const [numTimesResourceCalled, setNumTimesResourceCalled] = useState(0);

const getValueKey = (attrs = rest) => get(attrs, 'valueKey', 'value');

const getOptionValue = (option) =>
rest.raw && !rest.valueKey
? option
: get(option, getValueKey(rest), option);

if (_cacheUniq === undefined && watchParams) {
const params = {
customerId: rest.customerId,
Expand All @@ -58,6 +67,19 @@ const ResourceSelect = ({
setNumTimesResourceCalled(0);
}, [_cacheUniq]);

useEffect(() => {
if (selectByValue && previousOptions?.length >= 1) {
const matchedOption = find(
previousOptions,
(option) =>
getOptionValue(option)?.[selectByValue?.key] ===
selectByValue?.value ||
getOptionValue(option) === selectByValue?.value
);
setFieldValue(name, matchedOption);
}
}, [selectByValue, setFieldValue, previousOptions]);

const onFocusHandler = (...args) => {
if (onFocus) onFocus(...args);
};
Expand Down Expand Up @@ -356,6 +378,10 @@ ResourceSelect.propTypes = {
pageAll: PropTypes.bool,
pageAllSearchBy: PropTypes.func,
onError: PropTypes.func,
selectByValue: PropTypes.shape({
value: PropTypes.string,
key: PropTypes.string,
}),
};

ResourceSelect.defaultProps = {
Expand Down
69 changes: 49 additions & 20 deletions packages/select/src/Select.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { useField, useFormikContext } from 'formik';
Expand All @@ -7,6 +7,7 @@ import Creatable from 'react-select/creatable';
import { AsyncPaginate as Async } from 'react-select-async-paginate';
import get from 'lodash/get';
import has from 'lodash/has';
import find from 'lodash/find';
import isFunction from 'lodash/isFunction';
import isEqual from 'lodash/isEqual';

Expand Down Expand Up @@ -79,6 +80,49 @@ const Select = ({

const [newOptions, setNewOptions] = useState([]);

const [selectOptions, setSelectOptions] = useState([]);

useEffect(() => {
if (!attributes.loadOptions) {
if (allowSelectAll && attributes.isMulti) {
if (
[...options, ...newOptions].length > 0 &&
(values[name] === undefined ||
values[name] === null ||
values[name].length < [...options, ...newOptions].length)
) {
validateSelectAllOptions([...options, ...newOptions]);
setSelectOptions([selectAllOption, ...options, ...newOptions]);
} else {
setSelectOptions([...options, ...newOptions]);
}
} else {
setSelectOptions([...options, ...newOptions]);
}
}
}, [
attributes.loadOptions,
allowSelectAll,
attributes.isMulti,
newOptions,
options,
setSelectOptions,
]);

useEffect(() => {
// auto select an option
if (attributes.selectByValue && selectOptions?.length >= 1) {
const matchedOption = find(
options,
(option) =>
getOptionValue(option)?.[attributes.selectByValue?.key] ===
attributes.selectByValue?.value ||
getOptionValue(option) === attributes.selectByValue?.value
);
setFieldValue(name, matchedOption);
}
}, [attributes.selectByValue]);

let _cacheUniq = attributes.cacheUniq;

if (!Array.isArray(_cacheUniq)) {
Expand Down Expand Up @@ -248,25 +292,6 @@ const Select = ({
}
};

let selectOptions;
if (!attributes.loadOptions) {
if (allowSelectAll && attributes.isMulti) {
if (
[...options, ...newOptions].length > 0 &&
(values[name] === undefined ||
values[name] === null ||
values[name].length < [...options, ...newOptions].length)
) {
validateSelectAllOptions([...options, ...newOptions]);
selectOptions = [selectAllOption, ...options, ...newOptions];
} else {
selectOptions = [...options, ...newOptions];
}
} else {
selectOptions = [...options, ...newOptions];
}
}

if (attributes.loadOptions && allowSelectAll) {
// eslint-disable-next-line no-console
console.warn('allowSelectAll is ignored when loadOptions is defined.');
Expand Down Expand Up @@ -389,6 +414,10 @@ Select.propTypes = {
autofill: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
allowSelectAll: PropTypes.bool,
waitUntilFocused: PropTypes.bool,
selectByValue: PropTypes.shape({
value: PropTypes.string,
key: PropTypes.string,
}),
};

export default Select;
Loading