OwenMelbz / nova-radio-field

Provides a radio field for laravel nova with ability to toggle field visibility.
34 stars 31 forks source link

How can reset data when toggle the radio field? #5

Closed phuclh closed 5 years ago

phuclh commented 5 years ago

First of all, I want to say thank you because of the plugin.

#1 problem: Currently, when I toggle the radio, I can hide some fields. However, how can I set the value of these hidden fields to NULL? Because if I enter the value for these fields, after that I hide them and submit the form. These values are still inserted into the database.

#2 problem: How can I custom the validation for each case (hide/show). For example, when the fields display, I want to add required rule for them and remove that rule when these fields are hidden.

Thank you in advance!!!

OwenMelbz commented 5 years ago

Hi :)

1 Due to the way Nova works (very restrictive) there is no real way to apply any fancy callbacks when you change the visibility - the plugin works just by hiding/showing fields - There is no way to get access of other data and manipulate it easily.

2 Again just the way Nova works, the component on the frontend has no control over your backend validation.


You will need to utilise actual backend Laravel functionality to achieve this, there's 2 things you'd need to do to solve it.

1# Create a Model Observer

When you are saving your model, you will need to check the boolean toggle field to see what it is set to - and if it is set to the value which requires a null value you will need to set it there.

e.g.

<?php

namespace App\Observers;

use App\User;

class UserObserver {

    public function saving(User $user){
        if ($user->hide_photo) {  
            $user->photo_url = null
        }
    }

}

Obviously the code needs to be adapted for your use case, but that is the general process.


2. Normally in Laravel you can use Form Requests to make advance validation rules. However the Nova team have confirmed this is not possible -> https://github.com/laravel/nova-issues/issues/106#issuecomment-433490167

You "might" be able to (depending on your data) use these supported validation rules in your nova resource, e.g. the required_if required_unless etc etc - but if you cannot do it using them, then Nova is not yet feature ready for that