Auto populating Form Instance With Old Form Data

I'm using a Form class to create a form, all works fine except I can't seem to pre populate the form with old form data. For example, when a user completes the form, if they make an error I want to have the form fields populated with the values they already entered.

I'm following the documentation, but it's not very clear. Here is the controller method that handles the post request from the form. I thought I'd be able to just pass $_POST to the CreateSnapForm constructor, and the Form will auto populate:

public function createAction()
{
    if (!$this->security->checkToken()) {
        $this->flashSession->error('Sorry, we couldn\'t create your snap');
        return $this->response->redirect('/');
    }

    $form = new CreateSnapForm();

    # Tried ...
    // $form->bind($_POST, new Snap());

    if(!$form->isValid($this->request->getPost()))
    {
        $this->flashSession->error($form->getMessages()[0]);
        return $this->response->redirect('/');
    }

   ...
}

The documentation mentioned binding an entity, but the only entity I have is the model 'Snap', and if I bind that to the form, with the $_POST variable, it doens't work. Here is the model, it contains more properties than the form (not sure if that would cause a problem, hence why I posted the model). But to be honest I don't understand the reason why an entity must be provided to the form as I don't want the form to be responsible for saving the data:

use Phalcon\Mvc\Model;

class Snaps extends Model
{
    public $id;
    public $image;
    public $username;
    public $age;
    public $gender;
    public $votes;
    public $views;
    public $is_ghosted;
    public $browser;
    public $ip;
    public $proxy;
    public $deleted_at;
    public $created_at;
 }

Any ideas?



4.0k

When you call $form->isValid($userInput), form are populating data from $userInput. If you using redirect after validation, then you lose data. I'm using session variable for store user input data. After redirect, i populate form data from session variable. Sorry for my en.

Do not bind entity to form.

Just use regular $snapModel()->assign(data) and $snapModel->save() after form isPost() and isValid() checkong process!

P.S. If you submit form to itself (empty action attr), form fields will be populated with $_POST variable by default.