Conditional field

You can display a field based on a condition.

Only null or a Field instance, are allowed conditional values!

Example 1:

public bool $someBoolean = true;

protected function fields()
{
    return [
       $this->someBoolean 
          ? Input::make('Conditional Field 1')->required() 
          : Input::make('Conditional Field 2')->required(),
    ];
}

Example 2:

If the field depends on third party javascript libraries like FlatPickr (DatePicker field) or Trix.

You cannot switch visibility because the JS instance won't be destroyed, or the external script won't be loaded if the condition is false.

The way around it is to add class hidden to the field-root.

DatePicker::make(__('Birthday'), 'birthday')
    ->rootAttr($this->someBoolean ? [] : [ 'class' => 'hidden' ], true)
    ->locale('en')
    ->placeholder('Select a date...')
    ->includeExternalScripts(),

Observe:

When hiding fields with class hidden, the data properties will always exist in $form_data and $validated_data This is important in onCreateModel() and onUpdateModel()

You might want to filter out those properties when saving your component. Depending on the state of your condition. Please see this issue for a detailed example: https://github.com/tanthammar/tall-forms/issues/105#issuecomment-1029088173

Example 3:

protected function conditional()
{
    if ($this->something === "No") {
        return false; //the field will be omitted
    } else {
        return true; //the field will be included
    }
}

protected function fields()
{
    return [
        $this->conditional() 
            ? Input::make('Conditional Field')->required() 
            : null,
    ];
}

Example 4:

public bool $someBoolean = true;

protected function fields()
{
    return [
        $this->someMethod(),
    ];
}

protected function someMethod()
{
    if($this->someBoolean)) {
        return Input::make('Conditional Field')->required(); 
    } else {
        return null;
    }
}

Last updated