CodeIgniter Forums
display old value in form - 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: display old value in form (/showthread.php?tid=75737)



display old value in form - muuucho - 03-11-2020

I follow the Blog example from the docs and I'd like to have my form display old value when validation fails.
Controller:
Code:
public function create()
    {
        helper('form');
        $model = new NewsModel();

        if (! $this->validate([
            'title' => 'required|min_length[3]|max_length[255]',
            'body'  => 'required'
        ]))
        {
            if($_POST){
                return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
            }else{
                echo view('templates/header', ['title' => 'Create a news item']);
                echo view('news/create');
                echo view('templates/footer');
            }

        }
        else
        {
            $model->save([
                'title' => $this->request->getVar('title'),
                'slug'  => url_title($this->request->getVar('title')),
                'body'  => $this->request->getVar('body'),
            ]);
            echo view('news/success');
        }
    }
view:
PHP Code:
<h2><?= esc($title); ?></h2>

<?= \Config\Services::validation()->listErrors(); ?>

<form action="/news/create" method="post">

    <label for="title">Title</label>
    <input type="input" name="title" value="<?= old('title');?>" /><br />

    <label for="body">Text</label>
    <textarea name="body"></textarea><br />

    <input type="submit" name="submit" value="Create news item" />

</form> 
However, the form is blank when I post with a value in "title" and with an empty "body"


RE: display old value in form - InsiteFX - 03-11-2020

I' am taking this off the top of my head the way the forms are done in Myth/Auth.

I do recommend that you download it and view the controller and views with forms.

PHP Code:
$rules = [
    'title' => 'required|min_length[3]|max_length[255]',
    'body'  => 'required'
];

if (! 
$this->validate($rules))
{
    return redirect()->back()->withInput()->with('errors'$this->validator->getErrors());


Give that a try, I did not have time to test it but like I said Myth/Auth is a great learning module.


RE: display old value in form - muuucho - 09-29-2020

Thanks, that works