Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I repopulate form fields after validation errors with express-form?

Using node.js and express (2.5.9) with express-form.

How should I repopulate form fields with the submitted values?

I have a get and a post route. If there are validation errors when the form is posted, I redirect the user back to the get, the problem is that the repopulated locals don't show up (I do have autoLocals: true, so I assume it's because I am redirecting and res is reset.)

So how do you guys repopulate and what's your application flow, do you res.send instead of res.redirect and set up the whole thing again? That seems repetitive.

Here's an example of my post route:

app.post(

  '/projects/:id'

  , form(field("title").required("title", "Title is required)
  , function (req, res){

  if (!req.form.isValid){
    res.redirect('/project/'+req.params.id+'/edit');
  }
  else{
    // save to db
  }

});
like image 815
k00k Avatar asked May 22 '12 16:05

k00k


1 Answers

I am working with expressjs4.0 to repopulate the forms fields after validation you do:

router.route('/posts/new')
 .get(function(req, res) {
 res.render('posts/new', new Post({}));
});

The second argument in res.render below will set some variables in the view.

res.render('posts/new', new Post({}));

In my view I then set my form fields as follows:

...
<input type="text" name="title" value="<%- post.title %>">
<textarea name="article"><%- post.article %></textarea>
...

When you submit this form, it should be caught by your router like so:

router.route('/posts')
  .post(function(req, res) {
    var post = new Post(req.body)
      post.save(function(err) {
       if (err) {
         res.locals.errors = err.errors;
         res.locals.post = post;
         return res.render('posts/new');
       }
      return res.redirect('/posts');
  });
  ...
})

This line of code, resets the form fields in your view

res.locals.post = post;

I hope someone finds this useful ;)

like image 94
Kingsley Ijomah Avatar answered Sep 20 '22 11:09

Kingsley Ijomah