Перекрытие библиотеки select2 jquery ошибок проверки - PullRequest
0 голосов
/ 17 июня 2020

Я работаю над проектом, используя библиотеку валидатора jquery для проверки модальных форм. Проверка работает нормально, но у меня возникают проблемы с отображением проверки с полями формы выбора.

Я использую библиотеку select2 для стилизации раскрывающихся списков, и эта библиотека перекрывает исходный раскрывающийся список и сообщение проверки. Затем исходный код формы и вывод html, как вы можете видеть, есть элемент «em», показывающий сообщение проверки, но он перекрывается выбранным стилем.

{{ form_start(form, {'action': path('agregar_estantes')}) }}
    <div class="modal-header">
        <h5 class="modal-title m-0 font-weight-bold text-secondary"><i class="fas fa-fw fa-share-square"></i> Agregar Estante</h5>
    </div>
    <div class="modal-body">
        <div class="form-group">
            <div class="row">
                <div class="input-group col-6" style="padding-top: 15px">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1"><i class="far fa-fw fa-list-alt"></i></span>
                    </div>
                    {{ form_widget(form.numero) }}
                </div>
                <div class="input-group col-6" style="padding-top: 15px">
                    {{ form_widget(form.deposito) }}
                </div>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <div>
            <button type="submit" class="btn btn-primary btn-sm btn-icon-split createButton">
                <span class="icon text-white-50">
                    <i class="fas fa-save"></i>
                </span>
                <span class="text">Guardar</span>
            </button>
        </div>
        <div>
            <button type="button" class="btn btn-secondary btn-sm btn-icon-split" data-dismiss="modal">
                <span class="icon text-white-50">
                    <i class="fas fa-times"></i>
                </span>
                <span class="text">Cancelar</span>
            </button>
        </div>
    </div>

    <script type="text/javascript">
        $( document ).ready( function () {
            $(".createButton").click(function(e) {
                if (!$('#sac-form').valid()) {
                    e.preventDefault()
                }
            });

            $( "#sac-form" ).validate( {
                rules: {
                    'appbundle_estante[numero]': {
                        required: true,
                        digits: true,
                    },
                    'appbundle_estante[deposito]': {
                        required: true,
                    }
                },
                messages: {
                    'appbundle_estante[numero]': {
                        required: "Este campo es obligatorio.",
                        digits: "Este campo solo debe contener números."
                    },
                    'appbundle_estante[deposito]': {
                        required: "Este campo es obligatorio."
                    }
                },
                errorElement: "em",
                errorPlacement: function ( error, element ) {
                    error.addClass( "invalid-feedback" ).addClass("mb-n5").addClass("text-secondary").addClass("text-bold");
                    error.insertAfter( element );

                    //if ( element.prop( "type" ) === "checkbox" ) {
                    //    error.insertAfter( element.next( "label" ) );
                    //} else {
                    //    error.insertAfter( element );
                    //}
                },
            } );
        } );
    </script>

    <script>
        $(function () {
            $('select').each(function () {
                $(this).select2({
                    theme: 'bootstrap4',
                    width: 'style',
                    placeholder: $(this).attr('placeholder'),
                    allowClear: Boolean($(this).data('allow-clear')),
                });
            });
        });
    </script>
{{ form_end(form) }} 
<form name="appbundle_estante" method="post" action="/registro/estantes/agregar" id="sac-form" novalidate="novalidate">
    <div class="modal-header">
        <h5 class="modal-title m-0 font-weight-bold text-secondary"><i class="fas fa-fw fa-share-square"></i> Agregar Estante</h5>
    </div>
    <div class="modal-body">
        <div class="form-group">
            <div class="row">
                <div class="input-group col-6" style="padding-top: 15px">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1"><i class="far fa-fw fa-list-alt"></i></span>
                    </div>
                    <input type="text" id="appbundle_estante_numero" name="appbundle_estante[numero]" required="required" maxlength="10" autofocus="autofocus" class="form-control error" autocomplete="off" placeholder="Número del estante" aria-describedby="appbundle_estante_numero-error">
                    <em id="appbundle_estante_numero-error" class="error invalid-feedback mb-n5 text-secondary text-bold" style="display: inline;">Este campo es obligatorio.</em>
                </div>
                <div class="input-group col-6" style="padding-top: 15px">
                    <select id="appbundle_estante_deposito" name="appbundle_estante[deposito]" class="form-control select2-hidden-accessible error" placeholder="Seleccione un depósito" required="required" data-select2-id="appbundle_estante_deposito" tabindex="-1" aria-hidden="true" aria-describedby="appbundle_estante_deposito-error">
                        <option value="" data-select2-id="5"></option>
                        <option value="1">Nave 01</option>
                        <option value="2">Nave 02</option>
                        <option value="3">Nave 03</option>
                        <option value="4">Nave 04</option>
                        <option value="5">Nave 05</option>
                        <option value="7">Nave 06</option>
                    </select>
                    <em id="appbundle_estante_deposito-error" class="error invalid-feedback mb-n5 text-secondary text-bold" style="display: inline;">Este campo es obligatorio.</em>
                    <span class="select2 select2-container select2-container--bootstrap4" dir="ltr" data-select2-id="4">
                        <span class="selection">
                            <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-appbundle_estante_deposito-container">
                                <span class="select2-selection__rendered" id="select2-appbundle_estante_deposito-container" role="textbox" aria-readonly="true">
                                    <span class="select2-selection__placeholder">Seleccione un depósito</span>
                                </span>
                                <span class="select2-selection__arrow" role="presentation">
                                    <b role="presentation"></b>
                                </span>
                            </span>
                        </span>
                        <span class="dropdown-wrapper" aria-hidden="true"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <div>
            <button type="submit" class="btn btn-primary btn-sm btn-icon-split createButton">
                    <span class="icon text-white-50">
                        <i class="fas fa-save"></i>
                    </span>
                <span class="text">Guardar</span>
            </button>
        </div>
        <div>
            <button type="button" class="btn btn-secondary btn-sm btn-icon-split" data-dismiss="modal">
                    <span class="icon text-white-50">
                        <i class="fas fa-times"></i>
                    </span>
                <span class="text">Cancelar</span>
            </button>
        </div>
    </div>

    <script type="text/javascript">
        $( document ).ready( function () {
            $(".createButton").click(function(e) {
                if (!$('#sac-form').valid()) {
                    e.preventDefault()
                }
            });

            $( "#sac-form" ).validate( {
                rules: {
                    'appbundle_estante[numero]': {
                        required: true,
                        digits: true,
                    },
                    'appbundle_estante[deposito]': {
                        required: true,
                    }
                },
                messages: {
                    'appbundle_estante[numero]': {
                        required: "Este campo es obligatorio.",
                        digits: "Este campo solo debe contener números."
                    },
                    'appbundle_estante[deposito]': {
                        required: "Este campo es obligatorio."
                    }
                },
                errorElement: "em",
                errorPlacement: function ( error, element ) {
                    error.addClass( "invalid-feedback" ).addClass("mb-n5").addClass("text-secondary").addClass("text-bold");

                    //if ( element.prop( "type" ) === "checkbox" ) {
                    //    error.insertAfter( element.next( "label" ) );
                    //} else {
                    //    error.insertAfter( element );
                    //}
                },
            } );
        } );
    </script>

    <script>
        $(function () {
            $('select').each(function () {
                $(this).select2({
                    theme: 'bootstrap4',
                    width: 'style',
                    placeholder: $(this).attr('placeholder'),
                    allowClear: Boolean($(this).data('allow-clear')),
                });
            });
        });
    </script>
    <input type="hidden" id="appbundle_estante__token" name="appbundle_estante[_token]" value="oEMuc7h9AUlQqgWYIPppJFkbJZrvQceYzdLjo3qDaBE">
</form>

А вот и изображение вида, где пользователи не видят ошибку ...

enter image description here

Как я вижу, идея заключается в том, чтобы Элемент "em" после элемента "span", имеющего класс "select2". У меня нет опыта работы с javascript, код проверки был взят из примеров, поэтому вся помощь приветствуется. BR ...

PD: Простите мой английский sh

...