Skip to content

Conditions

Steve Pfisterer edited this page Aug 9, 2022 · 6 revisions

Conditions

ACF allows fields to be visible or hidden based on the values of other fields. These conditions work exactly like the field group locations work, being comprised by and / or logic, where or takes precedence to and.

use StoutLogic\AcfBuilder\FieldsBuilder;

$colors = new FieldsBuilder('colors');
$colors
    ->addRadio('color')
        ->addChoices('red', 'blue', 'green', 'other')
    ->addText('other_value')
        ->conditional('color', '==', 'other');

The above will show a text box if 'other' is selected from color, otherwise it will not be displayed in the admin.

Text values can also be used to hide and show fields:

use StoutLogic\AcfBuilder\FieldsBuilder;

$address = new FieldsBuilder('address');
$address
    ->addText('line1')
    ->addText('line2')
        ->conditional('line1', '!=', '');

The above will only show the address line 2 field if line 1 is filled out.

Complex Logic

Fields can be made visible or hidden based on more complex logic. The same rules apply as for field group locations

use StoutLogic\AcfBuilder\FieldsBuilder;

$banner = new FieldsBuilder('banner');
$banner
    ->addImage('background_image')
    ->addTrueFalse('add_title')
    ->addText('title')
        ->conditional('add_title', '==', '1')
    ->addRadio('title_color')
        ->addChoices('black', 'white')
        ->conditional('add_title', '==', '1')
    ->addRadio('title_background_color')
        ->addChoices(['transparent' => 'none'], 'black')
        ->conditional('add_title', '==', '1')
            ->and('title_color', '==', 'white');

This will display the Title Background Options only if a title is available and the title text color is white. The logic probably won't be as complex as field group locations logic, but it is there if needed.

Clone this wiki locally