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