return to view that fired the form in case of any error! Nojde+Express

Asked

Viewed 44 times

0

Good morning guys, it looks simple but I haven’t been able to on my own and I haven’t found it on the net, I just wanted to return to view that fired Submit, I have a simple registration screen... then I launch the route -> controller -> model. in the controller has the validators, in case of error I wanted to return to the already filled dialog!! follows below the code snippets :

Route:

router.route('/cadastros').post(home.loggedIn, cadastrosController.salvaCadastro);

Controller:

exports.salvaCadastro = (req, res, next) => {

    let contract = new ValidationContract();
    contract.hasMinLen(req.body.nome_cadastros, 3, 'O nome deve conter pelo menos 3 caracteres');
    contract.isRequired(req.body.telefone1_cadastros, 'O telefone é obrigatório');
    contract.hasMinLen(req.body.telefone1_cadastros, 3, 'O telefone deve conter pelo menos 3 caracteres');

    // Se os dados forem inválidos
    if (!contract.isValid()) {
        req.flash('error', contract.errors());
        //req.flash('error', "Erro ao tentar pesquisar.", e);
        res.redirect('/cadastros');
        return;
    }


    modelCadastro.salvarCadastro(req.body)
        .then(idRegistro => {
            req.flash('success', 'Dados salvos com sucesso!');
         //   return false;
            return res.redirect('/cadastros');
        }).catch(e => {
            req.flash('error', "Erro ao tentar salvar os dados.", e);
            res.redirect('/cadastros');
      //      return false;
        });
}

If you need more information please ask!!! Thank you in advance, guys!!

At +

1 answer

0

I got it right now (and on my own, it seems obvious but I got a little heheh), so that I have the doubt goes there...

I created a function that returns the res.Sender('view'....); passing the body, req and res to it,

from there in the function is like this...

module.exports.renderCadastrosView = function (res, req, result, titulo) {

    return res.render('cadastros', {
        dados: result,
        session: req.session,
        idempresa: result.empresa_cadastros,
        titulo: titulo
    });

}

and I call it that way:

     if (!form.isValid()) {
         req.flash('error', contract.errors());
         Utils.renderCadastrosView(res, req, req.body,'Editando cadastro');
         return; 
}

for now it’s over!! At+

Browser other questions tagged

You are not signed in. Login or sign up in order to post.