Symfony 4 Как добавить атрибут к ветке с помощью jquery? - PullRequest
0 голосов
/ 14 марта 2019

Я пытаюсь сделать форму с Symfony 4. Работает нормально.Но у меня есть проблема.У меня есть поле, чтобы написать комментарий.По умолчанию это не обязательно.Тем не менее, я хотел бы изменить это с помощью jquery.Это то, что я пытался сделать.

Вот моя веточка:

 <div class="information" id="informationForm">

        {{ form_row(recordForm.category) }}
        {{ form_row(recordForm.information) }}


        {{ form_label(recordForm.comment) }}
        {{ form_widget(recordForm.comment, {'attr': {'class': 'comment'}}) }}
        {{ form_errors(recordForm.comment) }}

        <button id="add_information_button" class="btn btn-primary">Ajouter un renseignement</button>
        <button id="count_div" class="btn btn-primary">Compter</button>
        <button class="remove_information_button btn btn-primary">Supprimer un renseignement</button>

    </div>

Вот яваскрипт:

   $('.information')
    .on("change", ".record_to_information_form_information", function (event) {
        event.preventDefault();
        var $commentState = $(this).find('option:selected').data('comment')

        //Test: to know if i received the attribute
        console.log($commentState)

        if($commentState===false){
            //the field isn't required
           // {{ form_widget(recordForm.comment, {'attr': {'required': 'false'}}) }}
        }else{
            //the field is required
            // {{ form_widget(recordForm.comment, {'attr': {'required': 'true'}}) }}
        }

    })
;

У вас есть предложения?

1 Ответ

0 голосов
/ 14 марта 2019

Вы можете переключать требуемое значение свойства из своего кода jQuery.

Я предполагаю, что атрибут data-comment имеет тип boolean, и он всегда установлен, поэтому ваш оператор переключения может выглядеть следующим образом:

$('.information')
    .on("change", ".record_to_information_form_information", function (event) {
        event.preventDefault();
        var $commentState = $(this).find('option:selected').data('comment');

        //Test: to know if i received the attribute
        console.log($commentState);

        $('.comment').prop('required', $commentState);
    });

Если вам нужно сделать что-то еще в вашем операторе if-else, вы можете просто оставить свое условие, указанное в примере:

if ($commentState === false) {
    //the field isn't required
    $('.comment').prop('required', false);
} else {
    //the field is required
    $('.comment').prop('required', true);
}
...