digital-creative / conditional-container

Provides an easy way to conditionally show and hide fields in your Nova resources.

Stars
2

Conditional Container

Latest Version on Packagist
Total Downloads
License

Laravel Nova Conditional Container in action

Provides an easy way to conditionally show and hide fields in your Nova resources.

Installation

You can install the package via composer:

composer require digital-creative/conditional-container

Usage

Basic demo showing the power of this field:


use DigitalCreative\ConditionalContainer\ConditionalContainer;
use DigitalCreative\ConditionalContainer\HasConditionalContainer;

class ExampleNovaResource extends Resource {

    use HasConditionalContainer; // Important!!

    public function fields(Request $request)
    {
        return [
    
            Select::make('Option', 'option')
                  ->options([
                      1 => 'Option 1',
                      2 => 'Option 2',
                      3 => 'Option 3',
                  ]),
    
            Text::make('Content', 'content')->rules('required'),
    
            /**
             * Only show field Text::make('Field A') if the value of option is equals 1
             */
            ConditionalContainer::make([ Text::make('Field A') ])
                                ->if('option = 1'),
    
            /**
             * Equivalent to: if($option === 2 && $content === 'hello world')
             */
            ConditionalContainer::make([ Text::make('Field B') ])
                                ->if('option = 2 AND content = "hello world"'),
    
            /**
             * Equivalent to: if(($option !== 2 && $content > 10) || $option === 3)
             */
            ConditionalContainer::make([ Text::make('Field C')->rules('required') ])
                                ->if('(option != 2 AND content > 10) OR option = 3'),
           
            /**
             * Example with Validation and nested ConditionalContainer!
             * Equivalent to: if($option === 3 || $content === 'demo')
             */
            ConditionalContainer::make([

                                    Text::make('Field D')->rules('required') // Yeah! validation works flawlessly!!
                                
                                    ConditionalContainer::make([ Text::make('Field E') ])
                                                        ->if('field_d = Nice!')
                                
                                ])
                                ->if('option = 3 OR content = demo')
        ];
    }

}

The ->if() method takes a single expression argument that follows this format:

(attribute COMPARATOR value) OPERATOR ...so on

you can build any complex logical operation by wrapping your condition in () examples:

ConditionalContainer::make(...)->if('first_name = John');
ConditionalContainer::make(...)->if('(first_name = John AND last_name = Doe) OR (first_name = foo AND NOT last_name = bar)');
ConditionalContainer::make(...)->if('first_name = John AND last_name = Doe');

you can chain multiple ->if() together to group your expressions by concern, example:

ConditionalContainer::make(...)
                    //->useAndOperator()
                    ->if('age > 18 AND gender = male')
                    ->if('A contains "some word"')
                    ->if('B contains "another word"');

by default the operation applied on each ->if() will be OR, therefore if any of the if methods evaluates to true the whole
operation will be considered truthy, if you want to execute an AND operation instead append ->useAndOperator() to the chain

Currently supported operators:

  • AND
  • OR
  • NOT
  • XOR
  • and parentheses

Currently supported comparators:

Comparator Description
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
== Equal
=== Identical
!= Not equal
!== Not Identical
truthy / boolean Validate against truthy values
contains / includes Check if input valid contains certain value
startsWith Check if input valid starts with certain value
endsWith Check if input valid ends with certain value

Examples

  • Display field only if user has selected file
[
    Image::make('Image'),
    ConditionalContainer::make([ Text::make('caption')->rules('required') ])
                        ->if('image truthy true'),
]
  • Display extra fields only if selected morph relation is of type Image or Video
[
    MorphTo::make('Resource Type', 'fileable')->types([
        App\Nova\Image::class,
        App\Nova\Video::class,
        App\Nova\File::class,
    ]),
    
    ConditionalContainer::make([ Image::make('thumbnail')->rules('required') ])
                        ->if(function () {
                            return 'fileable = ' . App\Nova\Image::uriKey();
                        })
                        ->if(function () {
                            return 'fileable = ' . App\Nova\Video::uriKey();
                        })
]
  • Display inline HTML only if Reason field is empty, show extra fields otherwise.
[
    Trix::make('Reason'),
    
    ConditionalContainer::make([ Text::make('Extra Information')->rules('required') ])
                        ->if('reason truthy true'),
    
    ConditionalContainer::make([
                            Heading::make('<p class="text-danger">Please write a good reason...</p>')->asHtml()
                        ])
                        ->if('reason truthy false'),
]

Notes

While inspired by nova-dependency-container,
ConditionalContainer takes a different approach to solve somewhat the same problem.
However, you can expect no issues with any third-party package at all!! as the way it was implemented
tries to be the least intrusive as possible.

However it hasn't yet been battle-tested against every use case out there but my own, so if you find any issue
please let us know or if you know how to fix it don't hesitate to submit a PR :)

Roadmap

  • Add more operators such as between, contains, startWith / endWith, length etc..
  • Add Support for depending on a field that is within another ConditionalContainer, example:
[
    Text::make('A'),
  
    ConditionalContainer::make([ Text::make('B') ])->if('a === foo') // Works!
    ConditionalContainer::make([ Text::make('C') ])->if('b === foo') // Doesnt work!
    ConditionalContainer::make([ 
        Text::make('D'),
        ConditionalContainer::make([ Text::make('E') ])->if('d === foo') // Works!
    ])->if('a === foo')
    
    // currently it's not possible to depend on a field that is within a ConditionalContainer as seen on the second ConditionalContainer above
]

License

The MIT License (MIT). Please see License File for more information.