index.js
98 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | const { Component } = wp.element; |
| 5 | const { BaseControl } = wp.components; |
| 6 | |
| 7 | /** |
| 8 | * Render ChosenSelect Control |
| 9 | */ |
| 10 | class ChosenSelect extends Component { |
| 11 | constructor( props ) { |
| 12 | super( props ); |
| 13 | |
| 14 | this.saveSetting = this.saveSetting.bind( this ); |
| 15 | this.saveState = this.saveState.bind( this ); |
| 16 | } |
| 17 | |
| 18 | saveSetting( name, value ) { |
| 19 | this.props.setAttributes( { |
| 20 | [ name ]: value, |
| 21 | } ); |
| 22 | } |
| 23 | |
| 24 | saveState( name, value ) { |
| 25 | this.setState( { |
| 26 | [ name ]: value, |
| 27 | } ); |
| 28 | } |
| 29 | |
| 30 | componentDidMount() { |
| 31 | const { value } = this.props; |
| 32 | |
| 33 | this.$el = jQuery( this.el ); |
| 34 | this.$el.val( value ); |
| 35 | |
| 36 | this.$input = this.$el.chosen( { |
| 37 | width: '100%', |
| 38 | } ).data( 'chosen' ); |
| 39 | |
| 40 | this.handleChange = this.handleChange.bind( this ); |
| 41 | |
| 42 | this.$el.on( 'change', this.handleChange ); |
| 43 | } |
| 44 | |
| 45 | componentWillUnmount() { |
| 46 | this.$el.off( 'change', this.handleChange ); |
| 47 | this.$el.chosen( 'destroy' ); |
| 48 | } |
| 49 | |
| 50 | handleChange( e ) { |
| 51 | this.props.onChange( e.target.value ); |
| 52 | } |
| 53 | |
| 54 | componentDidUpdate() { |
| 55 | const $searchField = jQuery( '.chosen-base-control' ).closest( '.chosen-container' ).find( '.chosen-search-input' ); |
| 56 | this.$input.search_field.autocomplete( { |
| 57 | source: function( request, response ) { |
| 58 | const data = { |
| 59 | action: 'give_block_donation_form_search_results', |
| 60 | search: request.term, |
| 61 | }; |
| 62 | |
| 63 | jQuery.post( ajaxurl, data, ( responseData ) => { |
| 64 | jQuery( '.give-block-chosen-select' ).empty(); |
| 65 | responseData = JSON.parse( responseData ); |
| 66 | |
| 67 | if ( responseData.length > 0 ) { |
| 68 | response( jQuery.map( responseData, function( item ) { |
| 69 | jQuery( '.give-block-chosen-select' ).append( '<option value="' + item.id + '">' + item.name + '</option>' ); |
| 70 | } ) ); |
| 71 | jQuery( '.give-block-chosen-select' ).trigger( 'chosen:updated' ); |
| 72 | $searchField.val( request.term ); |
| 73 | } |
| 74 | } ); |
| 75 | }, |
| 76 | } ); |
| 77 | } |
| 78 | |
| 79 | render() { |
| 80 | return ( |
| 81 | <BaseControl className="give-chosen-base-control"> |
| 82 | <select className="give-select give-select-chosen give-block-chosen-select" ref={ el => this.el = el }> |
| 83 | { this.props.options.map( ( option, index ) => |
| 84 | <option |
| 85 | key={ `${ option.label }-${ option.value }-${ index }` } |
| 86 | value={ option.value } |
| 87 | > |
| 88 | { option.label } |
| 89 | </option> |
| 90 | ) } |
| 91 | </select> |
| 92 | </BaseControl> |
| 93 | ); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | export default ChosenSelect; |
| 98 |