Yii2: Submit button with formaction outside of form tag

Created on 15 Jan 2020  路  4Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

Create a form, and put the submit button outside of the form.

And set the "form" attribute to the id of the form (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-form).

Now set the formaction attribute on the button.

What is the expected result?

On pressing that button, it should submit the form to my formaction.

What do you get instead?

It is submitted to the action of the form.

Additional info

It uses $form.on, and then filters by ":submit", since the submit button is not in the form, it is never going to set submitObject.
https://github.com/yiisoft/yii2/blob/master/framework/assets/yii.activeForm.js#L229

My current solution is:

$("[form=" + $form.attr("id") + "]:submit").on('mouseup.yiiActiveForm keyup.yiiActiveForm', function () {
    $form.data('yiiActiveForm').submitObject = $(this);
});

| Q | A
| ---------------- | ---
| Yii version | 2.0.32-dev
| PHP version | 7.4.1
| Operating system | Win 10

bug

Most helpful comment

Id should stay the same, to avoid conflicts when using Pjax you should ideally give your widgets their own unique ids instead of having auto generated ones.

Been a while since I've used jQuery but I think you'd need to include the current form so buttons within it are still picked up.

$("[form=" + $form.attr("id") + "]").add($form).on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
    $form.data('yiiActiveForm').submitObject = $(this);
});

All 4 comments

Do you want to submit a pull request fixing it?

I have a feeling my fix is suboptimal, I fear update through pjax might make problems.
Does the id of the form change on subsequent updates/validations?

Id should stay the same, to avoid conflicts when using Pjax you should ideally give your widgets their own unique ids instead of having auto generated ones.

Been a while since I've used jQuery but I think you'd need to include the current form so buttons within it are still picked up.

$("[form=" + $form.attr("id") + "]").add($form).on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
    $form.data('yiiActiveForm').submitObject = $(this);
});

Thx @alex-code that snippet helped finalizing it; pr done.

Was this page helpful?
0 / 5 - 0 ratings