CMB2 / CMB2

CMB2 is a developer's toolkit for building metaboxes, custom fields, and forms for WordPress that will blow your mind.
GNU General Public License v3.0
2.95k stars 572 forks source link

show_on_cb instant display !!! #840

Closed safiro closed 7 years ago

safiro commented 7 years ago

How to show 'Contact Info' instantly once the user select 'external' without waiting to update page ? is there any java script code to do that ?

add_action( 'cmb2_admin_init', 'cmb2_register_conditional_metabox' );
/**
 * Hook in and add a demo metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook.
 */
function cmb2_register_conditional_metabox() {
    /**
     * Metabox to save the 'status' where 'Internal' is the default.
     */
    $cmb = new_cmb2_box( array(
        'id'           => 'wiki_status_metabox',
        'title'        => 'Status Metabox',
        'object_types' => array( 'page', ), // Post type
    ) );

    $cmb->add_field( array(
        'name'    => 'Status',
        'id'      => 'wiki_status',
        'type'    => 'select',
        'default' => 'internal',
        'options' => array(
            'internal' => 'Internal',
            'external' => 'External',
        ),
    ) );

    /**
     * Metabox to conditionally display if the 'status' is set to 'External'.
     */
    $cmb = new_cmb2_box( array(
        'id'           => 'wiki_conditonal_metabox',
        'title'        => 'Contact Info',
        'object_types' => array( 'page', ), // Post type
        'show_on_cb' => 'cmb_only_show_for_external', // function should return a bool value
    ) );

    $cmb->add_field( array(
        'name'       => 'Email',
        'id'         => 'wiki_email',
        'type'       => 'text_email',
    ) );
}

/**
 * Only display a metabox if the page's 'status' is 'external'
 * @param  object $cmb CMB2 object
 * @return bool        True/false whether to show the metabox
 */
function cmb_only_show_for_external( $cmb ) {
    $status = get_post_meta( $cmb->object_id(), 'wiki_status', 1 );

    // Only show if status is 'external'
    return 'external' === $status;
}
tw2113 commented 7 years ago

I think this may help you out, but note it is a 3rd party solution: https://github.com/jcchavezs/cmb2-conditionals

bradp commented 7 years ago

Closing due to no movement here. Feel free to re-open if needed.

pgroot91 commented 4 years ago

Also having the same problem. Wonder if someone ever came up with a solution for aboves issue.

tw2113 commented 4 years ago

I think these two would be no-refresh needed:

https://github.com/awran5/CMB2-conditional-logic/ https://github.com/jcchavezs/cmb2-conditionals

but I can't recall off the top of my head and neither have gif demos