Symfony 4 如何使用 jquery 向树枝添加属性?

Symfony 4 How to add an attribute to a twig using jquery?

我正在尝试用 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>

这是 javascript:

   $('.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'}}) }}
        }

    })
;

你有什么建议吗?

您可以通过 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);
}