0

Hi today i must make a validation for files(there images) sending via ajax, i have huge problems with validation as annotation that work only when we send normaly form! not if files data coming via ajax :/ then that is code for symfony that can valid our collection of files and set error messages to their propertyPath.

$validatorImage = new Image(); // Symfony\Component\Validator\Constraints\Image
$validatorImage->mimeTypesMessage = 'image.mimeTypesMessage';
if ($form->isSubmitted()) {
    $i = 0;
    foreach ($form->get('images') as $image) {
        $errorList = $this->get('validator')->validateValue(
            $image->get('file')->getData(),
            $validatorImage
        );

        if (count($errorList)) {
            foreach ($errorList as $error) {
                $image->addError(
                    new FormError(
                        $error->getMessage(),
                        null,
                        array(),
                        null,
                        array('propertyPath' => 'children[images].data['.$i.'].file')
                    )
                );

            }
        }
        $i++;
    }
}

// is valid etc. our js action like similar to this one:

  $('form[name="product"]').on('submit', function () {
        var _self = $(this);
        var data = _self.serialize();
        data = new FormData(_self[0]);
        data.append('ajax',true);
        $.ajax({
            method: "POST",
            url: url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            enctype: 'multipart/form-data',
            });
            });

1 Answer 1

1

You can validate your entity without a form builder. Just know that validator is a service itself. You can use similar to something below in your controller :

// Collect data from ajax .
if ($request->isXmlHttpRequest()) {
    $data = $request->get('data');
    $files = $request->files;

    // Prepare your entity, Know you haven't uploaded image yet.
    $image = new Image();
    $image->setFile($files['image']);

    // Call your validator to validate Image Entity.
    $validator = $this->get('validator');
    $errors = $validator->validate($image);

    $errorMessages = array();
    if (count($errors) > 0) {
        foreach ($errors as $error) {
            $errorMessages[] = $error->getMessage();
        }
    }

    // send response to ajax accordingly. $errorMessages has all the errors as string.
    $response = array();
    return new JsonResponse($response);
}

Note : Variables and objects might be different for your use cases.

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks for reply, i test and rząd it again when i come back to home. $request->isXmlHttpRequest() this is a way to check if form is submited by ajax?
Yes, That will return true, if the form is submitted via ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.