How to create a custom backend form processing before submission and validation in Magento 2
For the standard jQuery .submit() method your submit event handler will be triggered after the standard form validation, but it could be inconvenient. Luckily, Magento 2 backend forms fire a custom beforeSubmit event:
Github code
1 2 3 |
if (false !== this._beforeSubmit(e.type, data)) { this.element.trigger('submit', e); } |
Github code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
_beforeSubmit: function(handlerName, data) { var submitData = {}; var event = new $.Event('beforeSubmit'); this.element.trigger(event, [submitData, handlerName]); data = $.extend( true, {}, this.options.handlersData[handlerName] || {}, submitData, data ); this.element.prop(this._processData(data)); return !event.isDefaultPrevented(); }, |
Thus, you can easily subscribe to it and run a custom processing before form both validation and submission. Examine the following example:
1 2 3 4 |
$textarea.closest('form').bind('beforeSubmit', function() { $textarea.val(editor.value()); $contentCompiled.val(editor.options.previewRender(editor.value())) }); |