Does logical condition work for other containers?
Version
- Carbon Fields: 2.1
- WordPress: 4.9.4
- PHP: 7.2.0
Expected Behavior
I want to Show / Hide a Field defined in post_meta Container based on a checkbox defined in theme_options Container.
Actual Behavior
Documentation says condition works within same container.
You can apply conditional logic to a field, using set_conditional_logic($rules), to show or hide it based on other field(s) in the same container.
I am trying
->set_conditional_logic( array( array( 'field' => 'my_checkbox', 'value' => true, )
is there is a way to achieve this?
Any help will be appreciated.
Thanks
Hi @muazzami ,
Conditionally showing/hiding fields depending on fields in other containers is not supported.
There is a workaround for your specific scenario, but it has its downsides:
- Make sure your theme options container is defined before your post meta container.
- Check the theme options field value and determine if you should define the post meta field at all.
Example:
Container::make( 'theme_otpions' )
->add_fields( array(
...
Field::make( 'text', 'parent_field' ),
...
) );
$should_define = carbon_get_theme_option( 'parent_field' ) === 'X';
$post_meta_fields = array( ... );
if ( $should_define ) {
$post_meta_fields[] = Field::make('text', 'child_field');
}
Container::make( 'post_meta' )
->add_fields( $post_meta_fields );
Downsides:
- This is not officially supported but it will work.
- During runtime (including on the front-end where you will want to get the value of the
child_field) trying to get the field value should result in an empty string, if it is undefined (even if there is a value stored for the field before it got "switched off").
Thank you for the response @atanas-angelov-dev
I figured this out and went with another workaround. I used a SELECT inside Post Meta to force user to select an option before relevant fields are displayed. Only downside is that I had to repeat it in every CPT, that was the main reason I wanted to use single Theme Option to enable / disable all of them.
Your workaround also make sense and I will keep it noted.
Thank you for the help.
Cheers