Search code examples
laravel-nova

How to show/hide Date input depending on which status is selected in the form?


In a Laravel 10 / Nova 4.27 app, I want to show the published_at field in the editor only if the status field has the value ACTIVE. Here is my current code:

    Badge::make(__('Status'), 'status')->required()
        ->options(ProductStatusEnum::getStatusSelectionItems())->hideFromDetail()->hideWhenUpdating()
        ->colors(ProductStatusEnum::getStatusColors(hexValue: true))->displayUsingLabels(),

    Date::make(__('Published at'), 'published_at')
        ->displayUsing(fn($value) => $value ? DateConv::getFormattedDateTime($value) : '--')
        ->showOnDetail(function () use ($status) { // in view mode "/nova/resources/products/17"
            return $status === ProductStatusEnum::ACTIVE;
        })
        ->showOnUpdating(function () use ($status) { // in edit mode "/nova/resources/products/17/edit"
            return $status === ProductStatusEnum::ACTIVE;
        })
        ->sortable(),

This setup works as expected when I open an existing model. However, is there a way to reactively show or hide the published_at date input in the form, depending on which status is selected?

UPDATED BLOCK #1:

If I try $field->visible code by @Jon Menard I got error :

Method Laravel\Nova\Fields\Date::visible does not exist.

In Dependent Fields block of docs there are hide/show methods example.

I try to follow it with code and defining depends method:

Date::make(__('Published at'), 'published_at')
    ->displayUsing(fn($value) => $value ? DateConv::getFormattedDateTime($value) : '--')
    ->hide()
    ->dependsOn(['status'], function (Date $field, NovaRequest $request, FormData $formData) {
        // Check if the status is 'ACTIVE'
        \Log::info(' -000 $formData->string(status)::');
        \Log::info(json_encode($formData->string('status')));

    })

But checking in log file value of $formData->string(status) I see empty string(maybe because I use enum for status field(not simple string)).

I tried to debug values of $field, $formData vars butI did not how I can status field from them...

I checked file vendor/laravel/nova/src/Fields/FormData.php, it has some methods, but nothing for enum field.

Any hints how get value of status field inside of dependsOn block ?


Solution

  • Take a look at the dependsOn functionality of a Laravel Nova Field.

    Something like this might work:

    Date::make(__('Published at'), 'published_at')
        ->displayUsing(fn($value) => $value ? DateConv::getFormattedDateTime($value) : '--')
        ->sortable()
        ->dependsOn(['status'], function (Date $field, NovaRequest $request, FormData $formData) {
            $field->hide();
            // Check if the status is 'ACTIVE'
            if ($formData->status === ProductStatusEnum::ACTIVE->value) {
                 $field->show();
            }
        }),