yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.23k stars 6.92k forks source link

Submit button with formaction outside of form tag #17805

Open My6UoT9 opened 4 years ago

My6UoT9 commented 4 years ago

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
samdark commented 4 years ago

Do you want to submit a pull request fixing it?

My6UoT9 commented 4 years ago

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?

alex-code commented 4 years ago

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);
});
My6UoT9 commented 4 years ago

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