#Nullable field validation

5 messages · Page 1 of 1 (latest)

lime phoenix
#

I have a form where a field is nullable, It looks like livewire is not creating the correct SQL statement to save the record:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column callcenter.time_switches.announcement_id at row 1 (SQL: update time_switches set announcement_id = , time_switches.updated_at = 2022-12-08 06:57:57 where id = 1)

shouldn't it read set announcement_id = null?

lime phoenix
#

So it looks like you need to hook into the updated event and set it to null if it's an empty string, doesn't Livewire have a similar middleware that laravel uses for trimming strings and converting empty strings to null:
https://phpexp.com/laravel-livewire/trim-strings-and-convert-empty-strings-to-null

#

Applied this trait to fix the issue:

<?php

namespace App\Http\Livewire\Traits;

trait TrimStringsAndConvertEmptyStringsToNull
{
    public function updatedTrimStringsAndConvertEmptyStringsToNull($name, $value)
    {
        if (is_string($value)) {
            $trimmed = trim($value);
            
            data_set($this, $name, $trimmed === '' ? null : $trimmed);
        }
    }
}
indigo wing
#

@lime phoenix yeah that's correct, due to the live nature of Livewire, if trim strings and convert to null were enabled, then a user typing say their full name in an input would never be able to type their first name and a space as the space would be stripped.

lime phoenix
#

Oh right, of course... so running on updated like this would be bad... maybe i need to do it on before saving