CodeIgniter Forums
Argument 2 passed to form_input() must be of the type string, null given - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Argument 2 passed to form_input() must be of the type string, null given (/showthread.php?tid=81080)



Argument 2 passed to form_input() must be of the type string, null given - frocco - 01-21-2022

Hello, can someone explain what is wrong with this?
Works fine if I just use <input statement.

Code:
public function new()
    {
        $document = new Document();

        return view('Documents/new', ['document' => $document]);
    }
    
// Form shared with edit.php and new.php
   <?= form_input(
        'title',
        old('title', esc($document->title)),
        ['class' => 'form-control'],
        'text'
    ) ?>

TypeError
Argument 2 passed to form_input() must be of the type string, null given


RE: Argument 2 passed to form_input() must be of the type string, null given - iRedds - 01-21-2022

The old() function returned null, while the form_input() function expects a string. Actually it is written in the text of an error.
The old() function returns null if no value is found and no default value is defined. But since you defined it, it means that your default value also returns null.

By saying it works fine you mean
PHP Code:
<input value="<?=esc($document->title)?>"

The esc() function ignores the null value and returns as is.
The null value is always converted to an empty string


RE: Argument 2 passed to form_input() must be of the type string, null given - frocco - 01-22-2022

I have to define it or my edit function does not fill the field.

I solved it by doing this.

Code:
<?= form_input(
        'title',
        old('title', esc($document->title) ?? ""),
        ['class' => 'form-control'],
        'text'
    ) ?>

is this the best way?


RE: Argument 2 passed to form_input() must be of the type string, null given - iRedds - 01-22-2022

If the Document is an instance of an Entity, then it seems to me that it would be better to define a default value.
PHP Code:
protected $attributes = ['title' => '']; 



RE: Argument 2 passed to form_input() must be of the type string, null given - frocco - 01-22-2022

(01-22-2022, 04:41 PM)iRedds Wrote: If the Document is an instance of an Entity, then it seems to me that it would be better to define a default value.
PHP Code:
protected $attributes = ['title' => '']; 

Thank you, I like your solution better.