useBlockAttributes.js
2 years ago
useFields.js
2 years ago
useIsAdvancedValidation.js
2 years ago
useIsUniqueFieldName.js
2 years ago
useSupport.js
2 years ago
useUniqKey.js
2 years ago
useUniqueNameOnDuplicate.js
2 years ago
useIsUniqueFieldName.js
81 lines
| 1 | import useRequestFields from '../../actions/hooks/useRequestFields'; |
| 2 | |
| 3 | const { |
| 4 | useSelect, |
| 5 | } = wp.data; |
| 6 | const { |
| 7 | useBlockEditContext, |
| 8 | } = wp.blockEditor; |
| 9 | |
| 10 | const { |
| 11 | __, |
| 12 | sprintf, |
| 13 | } = wp.i18n; |
| 14 | |
| 15 | const actionTypesMap = {}; |
| 16 | |
| 17 | for ( const { id, name } of window.jetFormActionTypes ) { |
| 18 | actionTypesMap[ id ] = name; |
| 19 | } |
| 20 | |
| 21 | function useIsUniqueFieldName() { |
| 22 | const { clientId } = useBlockEditContext(); |
| 23 | const actionFields = useRequestFields( |
| 24 | { returnOnEmptyCurrentAction: false }, |
| 25 | ); |
| 26 | |
| 27 | const { inFormFields, hasParent, fieldNames } = useSelect( |
| 28 | select => { |
| 29 | const currentBlock = select( 'jet-forms/fields' ). |
| 30 | getBlockById( clientId ); |
| 31 | |
| 32 | return { |
| 33 | hasParent: !!currentBlock?.parentBlock, |
| 34 | fieldNames: currentBlock?.fields?.map?.( |
| 35 | ( { value } ) => value ) ?? [], |
| 36 | inFormFields: select( 'jet-forms/fields' ). |
| 37 | isUniqueName( clientId ), |
| 38 | }; |
| 39 | }, |
| 40 | ); |
| 41 | |
| 42 | if ( !inFormFields ) { |
| 43 | return { |
| 44 | error: 'not_unique_in_fields', |
| 45 | message: __( |
| 46 | 'The form field name must be unique. Please change it', |
| 47 | 'jet-form-builder', |
| 48 | ), |
| 49 | }; |
| 50 | } |
| 51 | |
| 52 | if ( hasParent ) { |
| 53 | return {}; |
| 54 | } |
| 55 | |
| 56 | const computed = actionFields.find( |
| 57 | ( { value } ) => fieldNames.includes( value ) ); |
| 58 | |
| 59 | if ( ! computed ) { |
| 60 | return {}; |
| 61 | } |
| 62 | |
| 63 | return { |
| 64 | error: 'not_unique_in_actions', |
| 65 | message: computed?.from |
| 66 | ? sprintf( |
| 67 | __( |
| 68 | `The %s action already uses this field name. Please change it`, |
| 69 | 'jet-form-builder', |
| 70 | ), |
| 71 | actionTypesMap[ computed.from ], |
| 72 | ) |
| 73 | |
| 74 | : __( |
| 75 | 'The form field name must be unique. Please change it', |
| 76 | 'jet-form-builder', |
| 77 | ), |
| 78 | }; |
| 79 | } |
| 80 | |
| 81 | export default useIsUniqueFieldName; |