Skip to content

Latest commit

 

History

History
78 lines (68 loc) · 2.63 KB

File metadata and controls

78 lines (68 loc) · 2.63 KB

2.3 Custom initialization

So, you have added this part into your template

<html>
    <head>
        {{ include('FpJsFormValidatorBundle::javascripts.html.twig') }}
    </head>
    <body>

    </body>
</html>

Let's look at what's inside:

<script src="{{ asset('bundles/fpjsformvalidator/js/fp_js_validator.js') }}" type="text/javascript"></script>
{{ js_validator_config() }}
{{ init_js_validation() }}
  • the first line loads JS library
  • the second one sends some parameters to this library
  • the third line - this function processes all the forms which have been added to a queue before, and creates for each one its own JS validation model. So that if you have two or more forms on a page - all of them are processed by this function.

And if you want customize the initialization, you should leave the first and second lines at the header

<html>
    <head>
        <script src="{{ asset('bundles/fpjsformvalidator/js/fp_js_validator.js') }}" type="text/javascript"></script>
        {{ js_validator_config() }}
    </head>
    <body>

    </body>
</html>

and use the third line right at those places where you need it.

This function has three parameters:

    init_js_validation(form = null, onLoad = true, wrapped = true)
  • form By default this function processes all the forms which are added to the current queue. But if you want process only one specified form - put here a form name or a FormView instance of the necessary form. For example, you have comment and user forms on a page:
    {{ form(comment) }}
    init_js_validation(comment)
    ...
    ...
    {{ form(user) }}
    init_js_validation(user)
  • onLoad By default JS validation models are initialized on DocumentReady event, but if you need to init it later, on some other event, then you have to disable default behavior:
    {{ form(form) }}
    init_js_validation(null, false)
  • wrapper this parameter just defines if the result should be wrapped with <script type="text/javascript">...</script> tag

For example, you need to initialize JS validation only after an ajax request:

    {{ form(user) }}
    <script type="text/javascript">
        $.ajax({
            ...
            ...
            complete: function() {
                {{ init_js_validation(null, false, false) }}
            }
        });
    </script>
  • null means that all the available forms will be initialized
  • first false means that initialization will be performed right at the moment when the 'complete' function is called
  • second false means that JS code will not be wrapped with the 'script' tag