2
    $userData = (new User())
        ->setPersonCode(123)
        ->setPhone('+470002342342342');

    $userForm = $this->toolbar->getForm(UserType::class, $userData);

I'm creating form from entity class where is setted data. If now I try use:

$userForm->isValid();

I'm getting true, because form data is not submitted, how I can do validation, without setting manually data to form and submitting ?

2 Answers 2

2

If you don't want to submit data to a form, skip forms entirely; use the Validator service directly:

<?php

// (Assuming you're in a controller, otherwise inject the validator some other way.)

$userData = (new User())
    ->setPersonCode(123)
    ->setPhone('+470002342342342');

$validator = $this->get('validator');
$errors    = $validator->validate($userData);
$isValid   = count($errors) === 0;
Sign up to request clarification or add additional context in comments.

2 Comments

can I use in validator Assert\IsTrue annotations ?
If you've set those on the Model class you feed to the validate function, they will be recognized, yes.
0

Your question is worded a little strange and im not sure exactly what you want, If you want to manually set the data like above then call $form->submit() passing the user data.

$userData = (new User())
    ->setPersonCode(123)
    ->setPhone('+470002342342342');

$userForm = $this->toolbar->getForm(UserType::class);
$userForm->submit($userData);
if(!$userForm->isValid()){
    // handle errors
}

If you want to have the user submit data on a form then do something like this:

public function createUserAction(Request $request)
{
    $userForm = $this->toolbar->getForm(UserType::class);
    $userForm->handleRequest();
    if(!$userForm->isValid()){
        // handle errors
    }
}

$userForm->handleRequest(); will handle taking data that was submitted from the form on the page.

2 Comments

How I can call $form->sumbit() ? I not have data array.
@Wizard where are you expecting data to come from then? If its the form, use the second method

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.