Skip to content

Instantly share code, notes, and snippets.

@VinayaSathyanarayana
Forked from flowck/Example.js
Created November 29, 2017 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinayaSathyanarayana/21ed7b218c012eb649502aa9bb76fa0c to your computer and use it in GitHub Desktop.
Save VinayaSathyanarayana/21ed7b218c012eb649502aa9bb76fa0c to your computer and use it in GitHub Desktop.
[Keystone.js] Use admin forms outside admin #671
// Jade File
.
.
.
if exampleSubmitted
h1 Yeah, it works.
else
form(method='post')
input(type='hidden', name='action', value='example')
.form-group(class=validationErrors.name ? 'has-error' : null)
p Name
input(type='text', name='name', value=formData.name, placeholder="Insert your name")
.form-group(class=validationErrors.email ? 'has-error' : null)
p Age
input(type='number', name='age', value=formData.age, placeholder="Insert your age please")
.form-actions
button(type='submit') Send
// Model
var keystone = require('keystone'),
Types = keystone.Field.Types;
// Set new model
var Example = new keystone.List('Example', {
nocreate: true
});
// Set the fields of your model
Example.add({
name: { type: String, required: true, label: 'Age' },
age: { type: Number, label: 'Age' },
});
Example.defaultColumns = 'name, age';
// Regist your new model
Example.register();
// Controller for view example.jade
var keystone = require('keystone'),
Example = keystone.list('Example');
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res),
locals = res.locals;
// Set locals
locals.formData = req.body || {};
locals.validationErrors = {};
locals.exampleSubmitted = false;
// On POST requests, add the Example item to the database
view.on('post', { action: 'example' }, function(next) {
var newExample = new Example.model(),
updater = newExample.getUpdateHandler(req);
updater.process(req.body, {
flashErrors: true,
fields: 'name, age',
errorMessage: 'Something went wrong'
}, function(err) {
if (err) {
locals.validationErrors = err.errors;
} else {
locals.exampleSubmitted = true;
}
next();
});
});
view.render('example');
};
// Index file on root of routes
exports = module.exports = function(app) {
// Views
.
.
.
app.all('/example', routes.views.example);
.
.
.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment