laravel / nova-issues

556 stars 34 forks source link

dependsOn() gets stale data if fields are set programmatically #5517

Closed NorthNick closed 1 year ago

NorthNick commented 1 year ago

Description:

If a Nova field's value is set using setValue in a dependsOn function, and some other field depends on that first field, then the second field's dependsOn code does not receive the new value, but it gets the value that the field had before setValue was called. For example, take this Nova Resource code:

<?php

namespace App\Nova\Resources;

use App\Nova\Resource;
use Laravel\Nova\Fields\FormData;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;

class Bug extends Resource
{
    // Any model will do here: it's not actually used
    public static string $model = \App\Models\Foo::class;

    public function fields(NovaRequest $request) {
        return [
            Number::make('principal')->default(0)->step(1),
            Number::make('dependant')->default(0)->step(1)
                ->dependsOn(['principal'], function (Number $field, NovaRequest $request, FormData $formData) {
                    $field->setValue($formData->principal);
                }),
            Text::make('summary')
                ->dependsOn(['principal', 'dependant'], function (Text $field, NovaRequest $request, FormData $formData) {
                    $field->setValue("Principal: {$formData->principal}. Dependant: {$formData->dependant}");
                })
        ];
    }
}

This sets up three fields:

If you go to .../resources/bugs/new then it shows principal and dependent with values of 0 and summary with value "Principal: 0. Dependant: 0". Then use the number up arrow to increase principal's value to 1; dependant's value also increases to 1 in the UI but summary says "Principal: 1. Dependant: 0". Further changes to principal continue to change dependant, but the dependant value received by summary's dependsOn function remains at 0. If you change dependant's value in the UI, then summary receives the correct value, but then further changes to principal leave that value frozen as far as summary is concerned, even though dependant changes in the UI.

Expected behaviour

The values received by dependsOn should be the ones shown in the UI. If setValue is used to change a field's value, then that value should be passed in the next dependsOn call, if the user has not changed it.

github-actions[bot] commented 1 year ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.