Custom Fields
Re-Envisioned
Support MB Blocks problem initializing a text field value in a block.

  • Creator
    Topic
  • #23595
    Resolved DANIEL FITIPALDO R.
    Participant

    Hi,
    I want to initialize a text field in a block with a value stored in a custom post meta field which is calculated at ‘rwmb_after_save_post’ hook. At the beginning, I tried to change the value of the block’s text field using str_replace() in ‘post_content’ but I had some problems with incongruities between the value stored in the database (‘post_content’) and the value in the browser(‘The backup of this post in your browser is different from the version below.’). So, I decided to initialize the value using javascript but I have a problem to set the value in the js code. I am using: $(‘#my_block_text_field’).val(‘the_value_to_set’). Can you help me how to do that?
    You can find attached the block and fields definitions, the php enqueue script function code, and js code.

    <?php
    add_filter( 'rwmb_meta_boxes', 'your_prefix_register_meta_boxes' );
    
    function your_prefix_register_meta_boxes( $meta_boxes ) {
        $prefix = '';
    
        $meta_boxes[] = [
            'title'    => esc_html__( 'Test BLCK', 'text-domain' ),
            'id'       => 'test-blck',
            'fields'   => [
                [
                    'id'   => $prefix . 'text_hdsmywqrchf',
                    'type' => 'text',
                    'name' => esc_html__( 'Text Field Test BLCK', 'text-domain' ),
                ],
                [
                    'id'         => $prefix . 'taxonomy_advanced_yhwon6kcqb',
                    'type'       => 'taxonomy_advanced',
                    'name'       => esc_html__( 'Taxonomy Advanced Field', 'text-domain' ),
                    'taxonomy'   => 'test-type',
                    'field_type' => 'select',
                ],
                [
                    'id'                => $prefix . 'text_ey3ewpvlke',
                    'type'              => 'text',
                    'name'              => esc_html__( 'Amount text field', 'text-domain' ),
                    'size'              => 16,
                    'columns'           => 6,
                    'sanitize_callback' => 'xn_sanitize_money_field',
                ],
                [
                    'id'       => $prefix . 'text_41r32ufnhu8',
                    'type'     => 'text',
                    'name'     => esc_html__( 'Calculated Amount', 'text-domain' ),
                    'size'     => 16,
                    'columns'  => 6,
                    'readonly' => 1,
                ],
                [
                    'id'      => $prefix . 'radio_e0432gtno2d',
                    'name'    => esc_html__( 'Radio Test', 'text-domain' ),
                    'type'    => 'radio',
                    'std'     => 'no',
                    'options' => [
                        'yes' => esc_html__( 'Test 1', 'text-domain' ),
                        'no'  => esc_html__( 'Test 2', 'text-domain' ),
                    ],
                    'class'   => 'radiostyle',
                    'columns' => 12,
                ],
            ],
            'category' => 'layout',
            'icon'     => 'admin-appearance',
            'type'     => 'block',
            'mode'     => 'edit',
        ];
    
        return $meta_boxes;
    }

    This is the php code in my functions.php which is passing ok the params to javascript.

    function test_enqueue_scripts( $hook_suffix ) {
            if( in_array($hook_suffix, array('post.php', 'post-new.php') ) ){
                $screen = get_current_screen();
                if(is_object( $screen ) && ('test-pt' == $screen->post_type)){
                        $post_type_object = get_post_type_object( 'test-pt' );
                        $post_id = $post_type_object->ID;
                        // percentage value stored in post meta
                        $pct_test = rwmb_meta('number_uqjo7f193f', ['object_type' => 'post'], $post_id );
                        // calculate the value to be passed to javascript
                        $result = (empty($pct_test)) ? 0 : $pct_test;
                        wp_register_script('test_script', get_stylesheet_directory_uri() . '/test.js', array('jquery'),'1.1', true);
                        // ****
                        // prepare an array to be used by Javascript code
                        // ****
                        $ajax_url = admin_url( 'admin-ajax.php' );
                        $wp_nonce = wp_create_nonce( 'wp_rest' );
                        $array_params = array( 
                                'ajax_url' => $ajax_url,
                                'wp_nonce'=> $wp_nonce,
                                'result' => $result,
                            );
                        wp_localize_script( 'test_script', 'params_object', array ('json_params' => json_encode($array_params),));
                        wp_enqueue_script( 'test_script' );   
                }
            }   
    }
    add_action( 'admin_enqueue_scripts', 'test_enqueue_scripts' );

    And this is my javascript code:

    jQuery(document).ready(function($) {
        var myParamsStr = JSON.stringify(window.params_object);
        if (myParamsStr) {
            console.log(myParamsStr);
            var x = JSON.parse (myParamsStr);
            console.log(x);
            var y = JSON.parse (x.json_params);
            console.log(y);
            console.log(y.ajax_url);
            console.log(y.wp_nonce);
            console.log(y.result);
            $('#text_41r32ufnhu8').val(y.result); 
        }
    });
Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #23602
    Long Nguyen
    Moderator

    Hi,

    You can change the JavaScript code to

    jQuery(document).ready(function($) {
        
        $('body').on('change', function() {
            var myParamsStr = JSON.stringify(window.params_object);
            if (myParamsStr) {
                console.log(myParamsStr);
                var x = JSON.parse(myParamsStr);
                console.log(x);
                var y = JSON.parse(x.json_params);
                console.log(y.result);
                $('body').find('#text_41r32ufnhu8').val(y.result); 
            }
        });
        
    });

    to add the value for the text field text_41r32ufnhu8. But it will show the old value of the field number_uqjo7f193f because the Block Editor does not reload the page after update/save the post and the code

    wp_localize_script( 'test_script', 'params_object', array ('json_params' => json_encode($array_params),));

    still localize the old result.

    I think you can use some JavaScript code to get the field number_uqjo7f193f value on typing and show on the block field text_41r32ufnhu8 immediately.

    jQuery(document).ready(function($) {   
        $('body').on('keyup', function() {
            var number = $('#number_uqjo7f193f').val()
            $('body').find('#text_41r32ufnhu8').val(number); 
        });
    });
    #23642
    DANIEL FITIPALDO R.
    Participant

    Thanks!. Both solutions working fine! You can close the ticket as resolved.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.