Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ajax validation not working on an ActiveForm placed in a <table> tag #6886

Closed
pjacquemin opened this issue Jan 16, 2015 · 19 comments
Closed

Comments

@pjacquemin
Copy link

Hi,

It seems that there is a problem with ajax validation on an ActiveForm placed between "table" tags.
For example :

table class="table"

  • Modal begins here
  • activeform with ajaxvalidation true starts here
  • a "name" field is set here
  • activeform ends here
  • modal ends here

/table

It seems that no request is sent to controller when leaving the name field blank which is declared a required in form model. The ajax validation should display a message that name cannot be blank but nothing appens. After removing the "table" tag, it works perfectly. But is it normal ? When I have a look into the Firefox inspector, the "table" tag is removed.

Thanks you.

@lynicidn
Copy link
Contributor

see logs

@pjacquemin
Copy link
Author

I found nothing in log

@lynicidn
Copy link
Contributor

show response

@pjacquemin
Copy link
Author

The action that should be called is not called and so I have no response in my network inspector.
Here is the code :

<table class="table">
<?= $this->render('_save_template', ['search_model' => $search_model, 'template_model' => new TemplateForm()]); ?>
</table>

The "_save_template" file :

<?php
    Modal::begin([
        'header' => '<h2>Create template</h2>',
        'id' => 'save-template',
        'toggleButton' => [
            'tag' => 'a', 
            'label' => 'Save as template', 
            'href'=>'#save-template', 
            'data-target'=>'#save-template'
        ],
    ]);
    $form = ActiveForm::begin([
            'options' => ['enctype' => 'multipart/form-data'],
            'id' => 'save-template-form',
            'enableAjaxValidation'=> true, //=> ajax validation seems not working until this form is set between table tags
            'action' => Yii::$app->urlManager->createUrl(['template/create'])
    ]);
?>
<?= 
    Html::activeHiddenInput($template_model, 'search_json', ['value' => \yii\helpers\Json::encode($search_model)]);
?>
<?=
    $form->field($template_model, 'name')->textInput(['maxlength' => 40])->label('Name');
?>
<?=
    $form->field($template_model, 'type')->inline()->radioList(frontend\models\TemplateForm::getTypeList());
?>
<?=
    Html::submitButton('Save', ['class' => 'btn btn-primary']);
?>
<?php ActiveForm::end(); ?>
<?php
Modal::end();
?>

@lynicidn
Copy link
Contributor

see developer console (example firebug) for debug javascript and responses

@lynicidn
Copy link
Contributor

samdark/yii2-cookbook#26
i think table tag not blame. And u have not valid html

@pjacquemin
Copy link
Author

Thanks, but I used developer console as I said in my initial message ......

@kartik-v
Copy link
Contributor

Just a design suggestion (not sure if I got your complete use case). But there are some basic issues in your markup (where you are trying to embed a form element within another form). You could probably relocate the Modal content anywhere outside that does not overlap with other forms/javascript plugins reloading div etc. (e.g. place it at the end of the body). This does not conflict with your other markup and you can still show its content on click of a button from wherever you want. Lastly nested forms (form tag within another form tag) will not be an issue. Note nested forms are treated as invalid html by browsers.

@lynicidn
Copy link
Contributor

да о чем тут дискутировать :) это наверняка новшества браузеров, что они вырезают невалидный html

@lynicidn
Copy link
Contributor

вот примерно тут схожая проблема:
http://contactform7.com/why-isnt-my-ajax-contact-form-working-correctly/

HTML structure is not valid

Like other JavaScript, Contact Form 7’s JavaScript traverses and manipulates the structure of HTML. Therefore, if the original HTML structure is not valid, it will fail to work. You can check whether your HTML is valid or not with an HTML validator. I recommend XHTML-CSS Validator for use in such a case.

@lynicidn
Copy link
Contributor

(c) https://developer.mozilla.org/ru/docs/Web/Guide/HTML/Introduction

До появления HTML5 с его чёткими правилами парсирования HTML документов, браузеры интерпретировали невалидный код каждый по своему и поэтому результат мог выглядеть по разному. Браузеры прощали веб-разработчикам их ошибки, но к сожалению не одинаково и поэтому в случае невалидного кода результат был непредсказуемым. Теперь все браузеры начиная с Internet Explorer 10, Firefox 4, Opera 11.60, Chrome 18, или Safari 5 следуют стандарту, определяющему единый набор правил парсинга невалидного html кода. Поэтому при парсинге невалидного кода все современные браузеры построят одинковое дерево DOM элементов.

@mtangoo
Copy link
Contributor

mtangoo commented Jan 19, 2015

Please use English as some of us following does not know Russian (or whatever those Russian like stuffs mean)

@lynicidn
Copy link
Contributor

mtangoo: if easy - it problem with not valid html - global problem

@mtangoo
Copy link
Contributor

mtangoo commented Jan 20, 2015

👍

@gwelr
Copy link
Contributor

gwelr commented Jan 20, 2015

@kartik-v Thanks for your suggestion. I don't get why you are talking about nested forms? Except if Modal are forms (??), there is only one form tag in the above code.
As my colleague explained. the issue is very simple to understand, yet the problem is strange.
So let me explain again: We have a modal window with a form inside the modal. The form has ajax validation. The modal button is somewhere located in a table. When editing a field in the form, when the field loose focus, it should be ajax validated. Unfortunatly, no request is sent to controller eg when leaving required field blank. Our investigation have shown that when we remove the

tag (and the
), ajax validation works like a charm.

To those of view saying we have invalid HTML, could you elaborate what is wrong with the above html ?

@kartik-v
Copy link
Contributor

A modal is still a div markup with HTML embedded inside. Check your HTML source code... you will understand why its a nested form.

If I understand correct this is what you should see:

<form> <!-- your main form -->
    <input id="id1" type="text">
    <!-- your main form fields -->
    <!-- you begin your modal here -->
    <button type="button" class="btn btn-default" data-toggle="modal" data-target="#w0">
       Open modal
    </button>
    <div id="w0" class="modal">
        <div class="modal-dialog"><div class="modal-content">
            <div class="modal-body">
                <form>
                    <!-- NOTE: your nested form markup inside causing the INVALID HTML -->
                </form>
            </div>
        </div>
    </div>
</form>

What I suggested earlier is to move the modal elsewhere and keep only the button inside to toggle modal via javascript

<form> <!-- your main form -->
    <input id="id1" type="text">
    <!-- your main form fields -->
    <!-- you use only toggle button here  -->
    <button type="button" class="btn btn-default" onclick="launch_modal_func()">
       Open modal
    </button>
</form>

<!-- modal dialog is somewhere else to not conflict with nested forms -->
<div id="w0" class="modal">
        <div class="modal-dialog"><div class="modal-content">
            <div class="modal-body">
                <form>
                    <!-- NOTE: your nested form markup inside causing the INVALID HTML -->
                </form>
            </div>
        </div>
  </div></div>

@pjacquemin
Copy link
Author

I checked my HTML code and there is only one form. This form is in my modal and I don't see any nested form.

@lynicidn
Copy link
Contributor

try

<table><tr><td>{form here}</td></tr></table>

as valid html

@pjacquemin
Copy link
Author

@lynicidn You are right. I'm using a listview widget and now I moved the "table" tag inside the layout around {items}. So Its now working perfectly.
Thanks for your help.

@cebe cebe removed this from the 2.0.x milestone Jan 22, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants