Add and crop image with cropperjs

With Symfony, I need to add and crop images using CropperJS (Ajax) in my Users form. I added my field in UserType class:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', TextType::class, [
                'label' => 'Firstname',
                'attr' => [
                    'class' => 'form-control'
                ]
            ])
            ->add('lastname', TextType::class, [
                'label' => 'Lastname',
                'attr' => [
                    'class' => 'form-control'
                ]
            ])
            ->add('avatar', FileType::class, [
                'label' => 'Profile picture',
                'attr' => [
                    'onChange' => 'previewFile()'
                ]
            ])
        ;
    }

And in my template:

<div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <strong class="card-title">Media</strong>
                </div>
                <div class="card-body card-block">
                    {{ form_row(form.avatar) }}
                    <img src="" alt="" id="avatar">
                </div>
            </div>
        </div>

Add in my js file:

import Cropper from 'cropperjs/dist/cropper'

var preview = document.getElementById('avatar')
var file_input = document.getElementById('user_avatar')

function previewFile() {
    let file = file_input.files[0]
    let reader = new FileReader()

    reader.addEventListener('load', function (event) {
        preview.src = reader.result
    }, false)

    if(file){
        reader.readAsDataURL(file)
    }
}

The problem is when I try to add picture, normally the picture preview needs to be displayed in <img> tag, but nothing appears.
When I check the page console, I see this exception:

Uncaught ReferenceError: previewFile is not defined
at HTMLInputElement.onchange

Can I know the cause of this error?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *