Skip to content

Instantly share code, notes, and snippets.

@veritstudio
Last active October 12, 2018 09:34
Show Gist options
  • Save veritstudio/4729e2cda3d604c15493bc0faceb96ad to your computer and use it in GitHub Desktop.
Save veritstudio/4729e2cda3d604c15493bc0faceb96ad to your computer and use it in GitHub Desktop.
Get formKey for custom forms using JavaScript
define([
'jquery',
'uiComponent',
'ko',
'jquery/ui',
], function ($, Component, ko) {
'use strict';
return Component.extend({
defaults: {
template: 'VeritStudio_CustomForm/example',
},
formKeyInput: ko.observable(''),
initialize: async function () {
this._super();
this.createFormKeyInput('form_key', this.getFormKey());
return this;
},
/**
* Create hidden input with formKey
*
* @param name
* @param value
*/
createFormKeyInput: function (name, value) {
let input = `<input name="${name}" value="${value}" type="hidden">`;
this.formKeyInput.(input);
},
/**
* Get formKey
* @returns {string}
*/
getFormKey: function () {
return $.cookie('form_key');
}
});
});
<form action="#" method="post" data-bind="submit: submitForm">
<div data-bind="html: formKeyInput"></div>
<input type="text" id="your-name" name="your-name" value="" title="Your name">
<label class="label" for="your-name"><span>Your name</span></label>
<input type="email" id="your-email" name="your-email" value="" title="Your email">
<label class="label" for="your-email"><span>Your email</span></label>
<div class="actions-toolbar">
<div class="action-item">
<button type="submit" class="action submit primary">Send Email</button>
</div>
</div>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment