user8331511
user8331511

Reputation:

Passing form data express

Edit 2

I've tried the following.

routes

// competition form details
router.get('/dashboard/users/forms/competition-form/:id', ensureAuthenticated, (req, res) => {
  CompetitionForm.find(req.params.id, function(err, competition){
    res.render('dashboard/users/forms/competition-form.hbs', {
      pageTitle: 'Competition Form',
      users: competition
    });
  });
});

// competition form details post
router.post('/dashboard/users/forms/competition-form/:id', (req, res) => {
  CompetitionForm.findOneAndUpdate({ _id: req.params.id }, req.body, {upsert:true}, (err, competition) => {
    if (err) {
      console.log(`Error saving data:  ${err}`);
      return res.send('Error saving data');
    }

    res.redirect('/dashboard');
    console.log(req.body);
  });
});

input

<input type="text" class="form-control" name="schoolName" placeholder="Enter school name" value="{{competition.schoolName}}"

Still no luck.

Edit 1

So I have tested your example value="{{user.schoolName}}" with users: CompetitionForm in the route, however I get the field value from the user registration and not the CompetitionForm.

Here's what I have

user model

const express = require('express');
const mongoose = require('mongoose');

var app = express();

if (app.get('env') === 'production') {
  mongoose.connect(process.env.MONGODB_URI, { useMongoClient: true });
} else {
  mongoose.connect('mongodb://localhost/pol-development', { useMongoClient: true });
}

var db = mongoose.connection;
mongoose.Promise = global.Promise;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connection has been established");
});

var CompetitionFormSchema = mongoose.Schema({
  schoolName: String,
  competitionDate: String,
  competitionTime: String,
  competitionVenue: String,
  competitionTotalOfStudents: Number,
  competitionTotalParticipated: Number,
  competitionTotalPersonnel: Number,
  competitionJudge1Name: String,
  competitionJudge1Telephone: String,
  competitionJudge1Email: String,
  competitionJudge2Name: String,
  competitionJudge2Telephone: String,
  competitionJudge2Email: String,
  competitionJudge3Name: String,
  competitionJudge3Telephone: String,
  competitionJudge3Email: String,

  // admin fields
  competitionRequiredPhotos: Boolean,
  competitionRequiredCertifications: Boolean
});

var CompetitionForm = module.exports = mongoose.model('CompetitionForm', CompetitionFormSchema);

route

router.get('/dashboard/users/forms/competition-form/:id', ensureAuthenticated, (req, res) => {
  CompetitionForm.find(req.params.id, function(err, CompetitionForm){
    res.render('dashboard/users/forms/competition-form.hbs', {
      pageTitle: 'Competition Form',
      users: CompetitionForm
    });
  });
});

and for the form

<form action="/dashboard/users/forms/competition-form/{{user.id}}" method="post">

<label for="schoolName">School Name <span style="color: red">*</span></label>
<input type="text" class="form-control" name="schoolName" placeholder="Enter school name" value="{{user.schoolName}}" required>

Original

I have a competition form and a collection called competitionforms

enter image description here

I have the form working using the following routes

// competition form details
router.get('/dashboard/users/forms/competition-form/:id', ensureAuthenticated, (req, res) => {
  CompetitionForm.find(req.params.id, function(err, CompetitionForm){
    res.render('dashboard/users/forms/competition-form.hbs', {
      pageTitle: 'Competition Form',
      user_id: req.params.id
    });
  });
});

// competition form details post
router.post('/dashboard/users/forms/competition-form/:id', (req, res) => {
  CompetitionForm.findOneAndUpdate({ _id: req.params.id }, req.body, {upsert:true}, (err, competition) => {
    if (err) {
      console.log(`Error saving data:  ${err}`);
      return res.send('Error saving data');
    }

    res.redirect('/dashboard');
    console.log(req.body);
  });
});

Now I want to pass the form data so the user can see what they have entered should they go back to the form.

The form is using the users id

<form action="/dashboard/users/forms/competition-form/{{user_id}}" method="post">

So I have tried the following

{{competitionforms.user.schoolName}}, {{competitionforms.users.schoolName}}, {{users.competitionforms.schoolName}} and {{user.competitionforms.schoolName}}

I'm not sure what other combination I can try here.

Upvotes: 0

Views: 560

Answers (1)

Jason Cust
Jason Cust

Reputation: 10919

It's impossible to give you specifics without knowing what your template looks like but that is probably for the better since it appears there is a general misunderstanding of how Express renders the form from the template.

A very simplistic explanation is res.render takes a template and replaces any instances of specially formatted text, such as {{foo}}, with the values specified by the variable object as the second argument. So if that variable object had a foo property, that value would be used.

Example #1:

Template (template.hbs):

Hi {{name}}! Is {{favoriteColor}} your favorite color?

Express App:

res.render('template.hbs', { name: 'John', favoriteColor: 'green' });

Rendered Output:

Hi John! Is green your favorite color?

Example #2:

The provided variable object can also include embedded objects too!

Template (template.hbs):

Hi {{name.first}}! Is {{favorites.color}} your favorite color?

Express App:

res.render('template.hbs', { name: { first: 'John' }, favorites: { color: 'green' }});

Rendered Output:

Hi John! Is green your favorite color?

Bringing it back to your example, assuming your template looks something like the following:

Template (dashboard/users/forms/competition-form.hbs):

<form action="/dashboard/users/forms/competition-form/{{user.id}}" method="post">
  <label>School: <input type="text" name="schoolName" value="{{user.schoolName}}" /></label>

Then the updated Express code would look like:

router.get('/dashboard/users/forms/competition-form/:id', ensureAuthenticated, (req, res) => {
    CompetitionForm.find(req.params.id, function(err, competitionForm){
        res.render('dashboard/users/forms/competition-form.hbs', {
          pageTitle: 'Competition Form',
          user: competitionForm
        });
    });
});

This assumes your document object (competitionForm) has a property of schoolName.

For further reading on using Mustache templates in Express, checkout:


Edit:

Based on your Edit #2:

routes

// competition form details
router.get('/dashboard/users/forms/competition-form/:id', ensureAuthenticated, (req, res) => {
  CompetitionForm.find(req.params.id, function(err, competition) {
    res.render('dashboard/users/forms/competition-form.hbs', {
      pageTitle: 'Competition Form',
      users: competition
    });
  });
});

input

<input type="text" class="form-control" name="schoolName" placeholder="Enter school name" value="{{users.schoolName}}"

The template object properties must match the variable object properties so they can be accessed: { pageTitle: '...', users: {...} } ==> users.schoolName

Upvotes: 1

Related Questions