Welcome Guest, Not a member yet? Register   Sign In
display old value in form
#1

(This post was last modified: 03-11-2020, 07:26 AM by muuucho.)

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"
Reply
#2

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.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Thanks, that works
Reply




Theme © iAndrew 2016 - Forum software by © MyBB