@@ -7,8 +7,8 @@ import React, {
77 useMemo ,
88 useState
99} from 'react' ;
10- import _ from 'underscore' ;
1110import { Dropdown } from 'semantic-ui-react' ;
11+ import _ from 'underscore' ;
1212
1313type Item = {
1414 reference_table_id : number ,
@@ -28,6 +28,14 @@ const ReferenceCodeDropdown = (props: Props) => {
2828 const [ loading , setLoading ] = useState ( false ) ;
2929 const [ options , setOptions ] = useState ( [ ] ) ;
3030
31+ /**
32+ * Sets the "value" variable for the Dropdown component.
33+ */
34+ const value = useMemo ( ( ) => {
35+ const v = _ . pluck ( _ . filter ( props . value , ( x ) => ! x . _destroy ) , 'reference_code_id' ) ;
36+ return props . multiple ? v : _ . first ( v ) ;
37+ } , [ props . multiple , props . value ] ) ;
38+
3139 /**
3240 * Converts the passed ID to a reference code item.
3341 *
@@ -53,25 +61,37 @@ const ReferenceCodeDropdown = (props: Props) => {
5361 *
5462 * @type {(function(*, {value: *}): void)|* }
5563 */
56- const onChange = useCallback ( ( e , { value } ) => {
57- let values ;
64+ const onChange = useCallback ( ( e , data ) => {
65+ let referenceCodeIds ;
5866
5967 if ( props . multiple ) {
60- values = value ;
68+ referenceCodeIds = data . value ;
6169 } else {
62- values = _ . compact ( [ value ] ) ;
70+ referenceCodeIds = _ . compact ( [ data . value ] ) ;
6371 }
6472
65- props . onChange ( _ . map ( values , toItem ) ) ;
66- } , [ toItem , props . multiple , props . onChange ] ) ;
73+ const items = [ ] ;
6774
68- /**
69- * Sets the "value" variable for the Dropdown component.
70- */
71- const value = useMemo ( ( ) => {
72- const v = _ . pluck ( _ . filter ( props . value , ( x ) => ! x . _destroy ) , 'reference_code_id' ) ;
73- return props . multiple ? v : _ . first ( v ) ;
74- } , [ props . multiple , props . value ] ) ;
75+ // Find existing records or create new records
76+ _ . each ( referenceCodeIds , ( referenceCodeId ) => {
77+ let newValue = _ . findWhere ( props . value , { reference_code_id : referenceCodeId } ) ;
78+
79+ if ( ! newValue ) {
80+ newValue = toItem ( referenceCodeId ) ;
81+ }
82+
83+ items . push ( _ . omit ( newValue , '_destroy' ) ) ;
84+ } ) ;
85+
86+ // Mark records for delete
87+ _ . each ( props . value , ( v ) => {
88+ if ( v . id && ! _ . contains ( referenceCodeIds , v . reference_code_id ) ) {
89+ items . push ( { ...v , _destroy : true } ) ;
90+ }
91+ } ) ;
92+
93+ props . onChange ( items ) ;
94+ } , [ toItem , props . multiple , props . onChange , props . value ] ) ;
7595
7696 /**
7797 * Loads the list of reference codes from the server.
0 commit comments