Files
moloapp/example/app/FormUi.hpp
T

76 lines
2.5 KiB
C++
Raw Normal View History

#pragma once
// Shared HTML form rendering. One partial (form_page.html) draws every form:
// a summary box listing all failures with links to the fields, plus the
// message next to each invalid input. JSON clients keep the machine format.
#include <map>
#include <string>
#include <vector>
#include "../fw/Http.hpp"
#include "../fw/Templates.hpp"
#include "../fw/Validate.hpp"
namespace molo::example::app {
struct FormField {
std::string name;
std::string label;
std::string type = "text"; // text, email, number, password, textarea
std::string hint;
};
// True when the client asked for a page (browser) and not for JSON.
inline bool wants_html(const fw::Request& req) {
std::string accept = req.headers.get("Accept");
if (accept.find("text/html") != std::string::npos) return true;
return accept.find("application/json") == std::string::npos &&
req.headers.get("Content-Type").find("application/json") ==
std::string::npos;
}
struct FormView {
std::string title;
std::string action;
std::string submit = "Send";
std::string notice; // success message; hides the form when `done`
bool done = false;
std::vector<FormField> fields;
std::map<std::string, std::string> values;
const fw::ValidationError* error = nullptr;
fw::TemplateCtx ctx() const {
fw::TemplateCtx c;
c["title"] = title;
c["action"] = action;
c["submit"] = submit;
c["notice"] = notice;
c["done"] = std::string(done ? "true" : "");
std::map<std::string, std::string> by_field;
if (error) by_field = error->by_field();
fw::TemplateList rows, summary;
for (const auto& f : fields) {
auto v = values.find(f.name);
auto e = by_field.find(f.name);
std::string err = e == by_field.end() ? "" : e->second;
rows.push_back({{"name", f.name},
{"label", f.label},
{"type", f.type == "textarea" ? "" : f.type},
{"textarea", f.type == "textarea" ? "true" : ""},
{"hint", f.hint},
{"value", v == values.end() ? "" : v->second},
{"error", err},
{"invalid", err.empty() ? "" : "true"}});
if (!err.empty())
summary.push_back({{"name", f.name}, {"label", f.label}, {"message", err}});
}
c["fields"] = rows;
c["errors"] = summary;
c["error_count"] = std::string(summary.empty() ? "" : std::to_string(summary.size()));
return c;
}
};
} // namespace molo::example::app