0

Users can select an item from the list (the items are actually listed inside a DIV container). Upon selection, the item is added below with a leading checkbox in checked mode. When saved, the items get saved.

enter image description here

This flow works fine when I activate the Classic Widget editor.

But with the Block Widget editor, the checkbox values are simply getting ignored. I am not getting them inside $new_instance.

Here is the code written inside the update() method of the Widget:

function update( $new_instance, $old_instance ) {
   $instance = $new_instance
   ....
   ....
   // Unfortunately, these don't come through $new_instance
   $instance['groups'] = is_array($_POST['groups']) ? array_values($_POST['groups']) : array();
}

I am never getting any value inside $instance['groups'].

I added an additional textbox (<input type="hidden" name="instance-selected-groups" class="instance-selected-groups" value="' . $instance['instance-selected-groups'] . '" />) where I am storing comma separated item values using JavaScript like this.

enter image description here

I tried to grab these values in the update method like this:

if( empty( $instance['groups'] ) ) {
    if( strlen( trim( $_POST['instance-selected-groups'] ) ) > 0 ) {
        $instance['groups'] = array_pop( explode( ',', $_POST['instance-selected-groups'] ) );
        var_dump( $instance['groups'] );
    }
}

This doesn't work either.

3
  • You shouldn't be checking $_POST in a widget's update method. You should be using $new_instance and your inputs need a proper dynamic name for that to work. You should review the documentation for developing widgets as it seems like your approach is just incorrect: developer.wordpress.org/themes/functionality/widgets Commented Aug 2, 2022 at 12:00
  • Thank you @JacobPeattie for your quick reply. I am looking into the tutorial. However, the checkboxes get generated at client side, so I cannot get the instance for that. That is why I have to use $_POST approach for those. Moreover, this is an old widget and it runs perfectly fine with legacy widget editor, even today. But the problem starts onle on block editor. I can switch to classic widget editor, but rather I want to fix the issue and make it compatible for both editor modes. Commented Aug 2, 2022 at 12:48
  • 1
    Well your current approach won't work. I'd suggest looking at implementing this as a block. Commented Aug 2, 2022 at 13:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.