• Resolved dirkil

    (@dirkil)


    I created a custom post type ps_immobilie that has a field _psi_geo_plz like that:

    
    function add_geo_mb( $prefix, array $meta_boxes ) 
    {
        $meta_boxes['geo_metabox'] = 
        	array(
            'id'            => 'geo_metabox',
            'title'         => __( 'Ort', 'cmb2' ),
            'object_types'  => array( 'ps_immobilie', ), // Post type
            'context'       => 'normal',
            'priority'      => 'high',
            'show_names'    => true, // Show field names on the left
            'show_in_rest' => WP_REST_Server::ALLMETHODS,
            'fields'        => array(
            array(
                'name'       => __( 'PLZ', 'ps_immobilie' ),
                'public'     => true,
                'id'         => $prefix . 'geo_plz',
                'type'       => 'text',
                'show_in_rest' => WP_REST_Server::ALLMETHODS,
            ),
    
          ),
        );
        
        return $meta_boxes;	
    }
    

    I checked the CMB2 documentation on how to update the field with the Rest API an found the following URL:

    
    https://<domain>/wp-json/cmb2/v1/boxes/geo_metabox/fields/_psi_geo_plz?object_type=ps_immobilie&object_id=13784&value=44444
    

    When I send this request through Postman I get the following response (OK 200):

    
    {
        "type": "text",
        "name": "PLZ",
        "desc": "",
        "before": "",
        "after": "",
        "options": [],
        "text": [],
        "text_cb": "",
        "attributes": [],
        "protocols": null,
        "default": false,
        "default_cb": "",
        "classes": null,
        "classes_cb": "",
        "select_all_button": true,
        "multiple": false,
        "repeatable": false,
        "inline": false,
        "on_front": true,
        "show_names": true,
        "save_field": true,
        "date_format": "m\\/d\\/Y",
        "time_format": "h:i A",
        "description": "",
        "preview_size": [
            50,
            50
        ],
        "render_row_cb": "CMB2_Field::render_field_callback",
        "display_cb": "CMB2_Field::display_value_callback",
        "label": "CMB2_Field::label",
        "column": false,
        "js_dependencies": [],
        "public": true,
        "id": "_psi_geo_plz",
        "_id": "_psi_geo_plz",
        "_name": "_psi_geo_plz",
        "has_supporting_data": false,
        "update_field_value_permissions_check_cb": true,
        "value_updated": false,
        "value": "",
        "_links": {
            "self": [
                {
                    "href": "https://immoloader.powermaklersite.de/wp-json/cmb2/v1/boxes/geo_metabox/fields/_psi_geo_plz?object_id=13784&object_type=ps_immobilie"
                }
            ],
            "collection": [
                {
                    "href": "https://immoloader.powermaklersite.de/wp-json/cmb2/v1/boxes/geo_metabox/fields?object_id=13784&object_type=ps_immobilie"
                }
            ],
            "up": [
                {
                    "embeddable": true,
                    "href": "https://immoloader.powermaklersite.de/wp-json/cmb2/v1/boxes/geo_metabox?object_id=13784&object_type=ps_immobilie"
                }
            ]
        },
        "_embedded": {
            "up": [
                {
                    "id": "geo_metabox",
                    "title": "Ort",
                    "object_types": [
                        "ps_immobilie"
                    ],
                    "context": "normal",
                    "priority": "high",
                    "show_names": true,
                    "show_on": [],
                    "cmb_styles": true,
                    "enqueue_js": true,
                    "hookup": true,
                    "save_fields": true,
                    "closed": false,
                    "taxonomies": [],
                    "new_user_section": "add-new-user",
                    "new_term_section": true,
                    "show_in_rest": "GET, POST, PUT, PATCH, DELETE",
                    "classes": null,
                    "classes_cb": "",
                    "remove_box_wrap": false,
                    "mb_callback_args": null,
                    "message_cb": "",
                    "option_key": "",
                    "parent_slug": "",
                    "capability": "manage_options",
                    "icon_url": "",
                    "position": null,
                    "admin_menu_hook": "admin_menu",
                    "display_cb": false,
                    "save_button": "",
                    "disable_settings_errors": false,
                    "tab_group": "",
                    "update_field_value_permissions_check_cb": true,
                    "get_field_permissions_check_cb": true,
                    "delete_field_value_permissions_check_cb": true,
                    "get_box_permissions_check_cb": true,
                }
            ]
        }
    }
    

    The problem is that the field _psi_geo_plz is unchanged and blank. I would have expected it to contain 44444.

    In my functions.php I set the following:

    
    function custom_field_get_post_meta_cb($object, $field_name, $request){	
    	error_log('HEUREKA - Get!');
    	$metas = get_post_custom($post_id);
    	
    
    	foreach($metas as $key => $value) {
    		if(sizeof($value) == 1) {
    		$metas[$key] = $value[0];
    		}
    	}
    	return $metas;			
    }
    
    function custom_field_update_post_meta_cb($value, $object, $field_name){
    	error_log('HEUREKA - Update!');
    	error_log( print_r( $value, 1 ) );
    	return update_post_meta($object['id'], $field_name, $value); 
    }
    
    add_action('rest_api_init', function(){
    	
    	register_rest_field('ps_immobilie', '_psi_geo_plz', 
    		array(
    			'get_callback' => 'custom_field_get_post_meta_cb',
    			'update_callback' => 'custom_field_update_post_meta_cb')
    	); 
    
    });
    

    The function custom_field_update_post_meta_cb is not called at all. Maybe this is why the field does not get updated. But if so, what do I need to do in order to make it work?

    Any help is very much appreciated!

    Regards,
    Dirk.

Viewing 10 replies - 1 through 10 (of 10 total)
  • Plugin Contributor Michael Beckwith

    (@tw2113)

    The BenchPresser

    Before I go into attempting to debug anything with the code provided above, are you sure you’re using the latest version of CMB2? Or are you perhaps trying to use a version that’s bundled with a different theme/plugin?

    Asking, because the code in your add_geo_mb() function looks more like a now really old syntax for setting up metaboxes, as opposed to the object orientated version that we have now. I’m wondering if it’s possibly an issue with the version you have not having the needed support in the latest available versions.

    Thread Starter dirkil

    (@dirkil)

    I checked the version of the plugin and it’s 2.6.0. I wasn’t aware that there is a new way of setting up meta boxes. Our code is a couple of years old and now we would like to do some stuff with REST API which we didn’t do before.

    So, if the problem has nothing to do with the way of setting up meta boxes I would – for the time being – prefer to leave it as such and concentrate on how to get the REAT API part working. When this is solved I am more than happy to look into the more modern way of setting up mata boxes.

    Thank you for your support.

    Plugin Contributor Michael Beckwith

    (@tw2113)

    The BenchPresser

    Just pointing this part out for your own reference at the moment:

    https://github.com/CMB2/CMB2/blob/develop/example-functions.php#L109

    Seeing what I can do on the rest of it.

    Plugin Author Justin Sternberg

    (@jtsternberg)

    I just added a note to the bottom of the routes documentation: https://github.com/CMB2/CMB2/wiki/REST-API#routes

    The object_type REST API parameter does not refer to post-types, but rather the master object type, e.g. post, term, user, comments, or options-page.

    In your case, it would be post.

    Thread Starter dirkil

    (@dirkil)

    @justin

    I changed my URL from

    
    https://<domain>/wp-json/cmb2/v1/boxes/geo_metabox/fields/_psi_geo_plz?object_type=ps_immobilie&object_id=13784&value=44444
    

    to

    
    https://<domain>/wp-json/cmb2/v1/boxes/geo_metabox/fields/_psi_geo_plz?object_type=post&object_id=13784&value=44444
    

    But now I am getting the error: “Es wurde keine Route gefunden, die mit der URL und der Request-Methode identisch ist.”
    Traslated literally it means that no route was found for that URL.

    Thread Starter dirkil

    (@dirkil)

    Any new ideas? I would still be very much interested in finding a solution for this.

    So, any help is very much appreciated.

    Many thanks in advance!

    Plugin Author Justin Sternberg

    (@jtsternberg)

    Are you still using the exact code posted above? How is the add_geo_mb function hooked in?

    Plugin Author Justin Sternberg

    (@jtsternberg)

    If you want further help, I would encourage you to post all the code you are using with CMB2, so we can simply add it to our testing environment and test.

    Thread Starter dirkil

    (@dirkil)

    Hi Justin,

    I am totally interested in solving this; therefore I really appreciate you helping me out here.

    Here is the relevant code – at least what I think is relevant. When you need something else, let me know and I will post it here.

    
    
    function add_geo_mb( $prefix, array $meta_boxes ) 
    {
        $meta_boxes['geo_metabox'] = 
        	array(
            'id'            => 'geo_metabox',
            'title'         => __( 'Ort', 'cmb2' ),
            'object_types'  => array( 'ps_immobilie', ), // Post type
            'context'       => 'normal',
            'priority'      => 'high',
            'show_names'    => true, // Show field names on the left
            'show_in_rest' => WP_REST_Server::ALLMETHODS,
            // 'cmb_styles' => false, // false to disable the CMB stylesheet
            // 'closed'     => true, // Keep the metabox closed by default
            'fields'        => array(
            array(
                'name'       => __( 'PLZ', 'ps_immobilie' ),
                'public'     => true,
                'id'         => $prefix . 'geo_plz',
                'type'       => 'text',
                'show_in_rest' => WP_REST_Server::ALLMETHODS,
                //'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
            ),
            array(
                'name'       => __( 'Ort', 'ps_immobilie' ),
                
                'id'         => $prefix . 'geo_ort',
                'type'       => 'text',
                'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
            ),
            array(
                'name'       => __( 'Stra?e', 'ps_immobilie' ),
                
                'id'         => $prefix . 'geo_strasse',
                'type'       => 'text',
                'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
            ),
            array(
                'name'       => __( 'Hausnummer', 'ps_immobilie' ),
                
                'id'         => $prefix . 'geo_hausnr',
                'type'       => 'text',
                'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
            ),
            array(
                'name'       => __( 'Land', 'ps_immobilie' ),
                
                'id'         => $prefix . 'geo_land',
                'type'       => 'text',
                'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
            ),
    
            ),
        );
        
        return $meta_boxes;	
    }
    
    function cmb2_immobilie_metaboxes( array $meta_boxes ) 
    {
      // Start with an underscore to hide fields from custom fields list
      $prefix = '_psi_';
    
    	$meta_boxes = add_geo_mb($prefix, $meta_boxes);
    
    	return $meta_boxes;
    }	
    
    add_filter( 'cmb2_meta_boxes', 'cmb2_immobilie_metaboxes' );
    
    function custom_field_get_post_meta_cb($object, $field_name, $request){	
    	error_log('HEUREKA - Get!');
    	$metas = get_post_custom($post_id);
    	
    
    	foreach($metas as $key => $value) {
    		if(sizeof($value) == 1) {
    		$metas[$key] = $value[0];
    		}
    	}
    	return $metas;			
    }
    
    function custom_field_update_post_meta_cb($value, $object, $field_name){
    	error_log('HEUREKA - Update!');
    	error_log( print_r( $value, 1 ) );
    	return update_post_meta($object['id'], $field_name, $value); 
    }
    
    add_action('rest_api_init', function(){
    	
    	register_rest_field('ps_immobilie', '_psi_geo_plz', 
    		array(
    			'get_callback' => 'custom_field_get_post_meta_cb',
    			'update_callback' => 'custom_field_update_post_meta_cb')
    	); 
    
    });

    I really hope we can solve this.

    Regards,
    Dirk

    Plugin Author Justin Sternberg

    (@jtsternberg)

    Hello Dirk,

    I don’t have your ps_immobilie post-type registration code, so I just used a post-type I have setup locally for testing. You are probably aware, but you’ll have to use some sort of authentication to make write requests. In my case, on my local testing site, I use the Basic auth plugin for the REST API. Using the following request, it successfully updates the value each time:

    curl --request POST --url "https://<domain>/wp-json/cmb2/v1/boxes/geo_metabox/fields/_psi_geo_plz?object_type=post&object_id=1084&value=$(date)" --header 'authorization: Basic <basicauth_creds>'

    So based on that, if it’s not working for you there is likely something else going on with your setup. Maybe try disabling other plugins, or trying to use a default WordPress theme and test agaiin.

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘RestAPI: cmb2 field not updated’ is closed to new replies.