-
-
Save robincornett/d25588a5429b7341bf887d690b484630 to your computer and use it in GitHub Desktop.
This is my extracted onChange function for what to do when the post_type value is changed in a Gutenberg block. I have two dependent selectControl elements which should have their options updated. At this time, I can update the value of the dependent controls, but I can't figure how to change the list of options.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onChangePostType( select_id, value, props, setAttributes ) { | |
const data = { | |
action: 'my_ajax_action', | |
security: 'my_nonce' | |
}; | |
if ( 'post_type' === select_id ) { | |
data.post_type = value; | |
} else { | |
data.post_type = props.post_type; | |
data.taxonomy = value; | |
} | |
$.post( 'my_ajax_url', data, function ( response ) { | |
if ( undefined !== response.success && false === response.success ) { | |
return; | |
} | |
var jsonData = $.parseJSON( response ); | |
/** | |
* My jsonData has three arrays in it: a list of all the posts | |
* of the selected post_type, a list of the taxonomies assigned | |
* to the selected post_type, and a list of the terms assigned to | |
* the first post_type taxonomy. | |
* | |
* What I would like to have happen is for the options in the | |
* selectControl elements for the taxonomy and term to update | |
* when the post_type is changed. The data is there, but how do I | |
* swap out the list of options? On the widgets admin screen, I | |
* target the select elements by ID, remove the options, and replace | |
* them. | |
*/ | |
if ( 'post_type' === select_id ) { | |
props.setAttributes( { | |
taxonomy: 'post_tag', // present as a test--I can update the value of the taxonomy when the post_type changes | |
options: _getOptions( jsonData.taxonomies ) // this doesn't do anything | |
} ); | |
} | |
} ); | |
} | |
function _getOptions( data ) { | |
var options = []; | |
var i = 0; | |
$.each( data, function ( key, value ) { | |
options[i] = { | |
value: key, | |
label: value | |
}; | |
i ++; | |
} ); | |
return options; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment