Search code examples
http-redirectcontact-formfat-free-framework

fatfree framework, repopulate fields after unsuccessful validation


I have GET route which shows the contact form, and POST route when user submits the form, then in my controller method I do some validation tests on data being submitted.. how would I now send user back to form if data is not valid, with entered data being re-populated in form fields?

I know I can use isset(@POST.fieldname) in my template, but what's the right way of sending entered data back to that view, and how to redirect user back to the form? Is the f3->reroute method right way of doing that?


Solution

  • I think you can take as a rule to include input data inside your form views. This way, any form view will be easily reusable with any source of data.

    For example:

    Your form view:

    <form action="" method="post">
      <input type="text" name="email" value="{{ @@input.email }}"/>
      <input type="text" name="message" value="{{ @@input.message }}"/>
      <button type="submit">Submit form</button>
    </form>
    

    Your controller class:

    class myController {
    
      function get($f3) {
        $this->renderForm();
      }
    
      function post($f3) {
        $post=$f3->clean($_POST);
        //validate form data here
        if ($form_validated) {//valid form data
    
        } else //invalid form data
          $this->renderForm($post);
      }
    
      protected function renderForm($input=array()) {
        $tpl=Template::instance();
        //variant 1:
        echo $tpl->render('form.html','text/html',array('input'=>$input))
        // or variant 2:
        Base::instance()->set('input',$input);
        echo $tpl->render('form.html');
      }
    
    }
    

    In some other contexts, you can feed a form view with data coming from a db mapper (for example when editing an entry from a back-office): $this->renderForm($mapper->cast())