dongmufen8105 2016-08-16 02:12
浏览 29
已采纳

Symfony 2.3如何通过复选框隐藏/显示图像

My problem is that I want to be able to hide or show an uploaded image via checkbox, i.e. I uploaded image A, a checkbox will come along with it that if checked hide image, when unchecked show image. I was thinking of giving them values like 1 and 0 but I have no idea where should I do this, is it in Javascript? or in symfony forms/entities/controller?

Any help would be much appreciated, thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanjuan1103 2016-08-16 08:53
    关注

    The best way for you will be to use Javascript. I would suggest you the following steps:

    1/ Integrate a checkbox in Symfony form .

    2/ Hide the checkbox with javascript.

    3/ When the image is uploaded, display the image (see an extract of code below for that step) + display the checkbox

    4/ Detect the event (click on the checkbox), get the value of it and according to its value, hide or display the image

    An extract of code that might help you for displaying the image:

    $(function() {
    $(".upload-file input").each(function(){
        $(this).on("change", function(){
            var files = !!this.files ? this.files : [];
            if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
    
            if (/^image/.test( files[0].type)){ // only image file
                var reader = new FileReader(); // instance of the FileReader
                reader.readAsDataURL(files[0]); // read the local file
    
                reader.onloadend = function(){ // set image data as background of div
                    $("#imagePreview").css("background-image", "url("+this.result+")");
    
                    // Show picture fields
                    if (typeof hideShowFieldsPictureForm !== 'undefined') {
                        hideShowFieldsPictureForm();
                    }
                    if ($('#hideShowPixFields').length) {
                        $('#hideShowPixFields').removeClass('hidden');
                    }
    
                };
            }
        });
    });
    
    if ($('#uploadFileBtn').length) {
        $('#uploadFileBtn').click(function() {
            $('.upload-file input[type=file]').click();
        });
    }
    

    });

    And in the twig:

       {# Main Picture #}
        <table class="upload-file">
            <tr>{{ form_errors(form.picture.file) }}</tr>
            <tr>
                <td>
                    {{ form_widget(form.picture.file) }}
                    <div id="imagePreview"></div>
                </td>
            </tr>
        </table>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?