传递表格数据快递

时间:2018-01-20 00:51:01

标签: node.js express handlebars.js

修改2

我已尝试过以下内容。

路由

// 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 type="text" class="form-control" name="schoolName" placeholder="Enter school name" value="{{competition.schoolName}}"

仍然没有运气。

修改1

所以我在路由中测试了您的示例value="{{user.schoolName}}"users: CompetitionForm,但是我从用户注册而不是CompetitionForm获取字段值。

这是我拥有的

用户模型

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);

路线

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
    });
  });
});

和表格

<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>

原始

我有一个竞赛表格和一个名为competitionforms

的集合

enter image description here

我的表单使用以下路由

// 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);
  });
});

现在我想传递表单数据,以便用户在返回表单时可以看到他们输入的内容。

表单正在使用用户ID

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

所以我尝试了以下

{{competitionforms.user.schoolName}}{{competitionforms.users.schoolName}}{{users.competitionforms.schoolName}}{{user.competitionforms.schoolName}}

我不确定我在这里可以尝试的其他组合。

1 个答案:

答案 0 :(得分:1)

如果不知道你的模板是什么样子就不可能给你细节,但这可能会更好,因为看起来对于Express如何从模板中呈现表单存在普遍的误解。

一个非常简单的解释是res.render接受一个模板,并将特殊格式文本的任何实例(例如{{foo}})替换为变量对象指定的值作为第二个参数。因此,如果该变量对象具有foo属性,则将使用该值。

示例#1:

模板(template.hbs):

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

Express App:

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

渲染输出:

Hi John! Is green your favorite color?

示例#2:

提供的变量对象也可以包含嵌入对象!

模板(template.hbs):

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

Express App:

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

渲染输出:

Hi John! Is green your favorite color?

将它带回到您的示例中,假设您的模板类似于以下内容:

模板(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>

然后更新的Express代码如下:

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
        });
    });
});

这假设您的文档对象(competitionForm)具有schoolName的属性。

有关在Express中使用Mustache模板的进一步阅读,请结帐:

编辑:

基于您的编辑#2:

路由

// 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 type="text" class="form-control" name="schoolName" placeholder="Enter school name" value="{{users.schoolName}}"

模板对象属性必须匹配变量对象属性,以便可以访问它们:{ pageTitle: '...', users: {...} } ==&gt; users.schoolName