Skip to content

Instantly share code, notes, and snippets.

@cpilsworth
Last active April 21, 2016 13:42
Show Gist options
  • Save cpilsworth/828dc1d12404467a3f8f to your computer and use it in GitHub Desktop.
Save cpilsworth/828dc1d12404467a3f8f to your computer and use it in GitHub Desktop.
Using acs-aem-commons forms functionality with Sightly
<sly data-sly-use.form="test.js"></sly>
sly data-sly-test.errors="${form.validate}"></sly>
<sly data-sly-test="${errors}">${form.renderForm}</sly>
<sly data-sly-test="${!errors}">${form.redirectSuccess}</sly>
use(function () {
"use strict";
var formName = 'demo',
helper = sling.getService(Packages.com.adobe.acs.commons.forms.helpers.PostRedirectGetFormHelper),
form = helper.getForm(formName, request, response);
return {
form: form,
action: helper.getAction(currentPage),
formInputs: function() { return helper.getFormInputsHTML(form); },
data: function() { return form.getData(); },
errors: function() { return form.getErrors(); },
redirectSuccess: function() { response.sendRedirect("/content/test.success.html"); },
renderForm: function() { helper.renderForm(form, currentPage, request, response); },
validate: function() {
if (form.get("myField") === null || form.get("myField").length() < 10) {
form.setError("myField", "What kind of answer is: " + form.get("myField"));
}
return form.getErrors();
}
};
});
<form method="post" action="${form.action}" data-sly-use.form="test.js">
${form.formInputs @ context='unsafe'}
<fieldset>
<legend>Form Demo</legend>
<div data-sly-test.myFieldError="${form.errors['myField']}">${myFieldError}</div>
<label data-sly-attribute.class="${myFieldError ? 'error' : ''}">My Field:</label>
<input type="text" name="myField" value="${form.data['myField']}"/>
<input type="submit" value="Submit"/>
</fieldset>
</form>
@cpilsworth
Copy link
Author

The validate function could work well with Joi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment