Reputation: 1321
The form is never valid, but $form->getErrors()
gives no error.
Since its gonna be a REST API test it with DEV HTTP client
test data is
Header:
Content-Type:application/json
Body:
{"username":"sad","password":"123","email":"[email protected]"}
I don't have any validation.yml file
Is there any any method to find out whats going wrong (error Message)?
public function postUserAction(Request $request)
{
return $this->processForm(new User(),$request);
}
private function processForm(User $user, Request $request )
{
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
if ($form->isValid()) {
return array('form' => 'valid');
}
return \FOS\RestBundle\View\View::create($form->getErrors(),400);
}
Upvotes: 5
Views: 4873
Reputation: 722
I am late to reply to this one but, all answers are wrong. submit
should be avoided and use handleRequest
instead. Read this. That form was not valid with handleRequest
because UserType
was missing one of the next:
In UserType
class getName
function should return empty string and csrf_protection
should be disabled (IF you are using API
approach where form
was not generated
from your Symfony2 project):
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'UserApiBundle\Entity\User',
'csrf_protection' => false,
));
}
public function getName()
{
return '';
}
submit
would not check for that and it is a bad approach for POST
. You could use it for PUT
request to update a User
where password
field would not be submitted for xyz reasons (ex: permissions).
$form->submit($request, false);
It is hard to dig for form
errors in Symfony2. You can use this function to get errors:
public function getErrors($form)
{
$errors = array();
foreach ($form as $fieldName => $formField) {
$currentError = $formField->getErrors();
if ($currentError->current()) {
$current = $currentError->current();
$errors[$fieldName] = $current->getMessage();
}
}
return $errors;
}
Upvotes: 0
Reputation: 6733
This worked for me:
$form = $this->createForm(new UserType(), $user);
$jsonData = json_decode($request->getContent(), true); // "true" to get an associative array
if ('POST' === $request->getMethod()) {
$form->bind($jsonData);
...
}
Upvotes: 1
Reputation: 1321
After a little debug: isValid() checks form several things eg if the form has been submitted. It wasnt, so i changed to
...
$form = $this->createForm(new UserType(), $user);
//$form->handleRequest($request);
$form->submit($request);
if ($form->isValid()) {
...
now its valid.
Upvotes: 3
Reputation: 160903
When debugging a form validation,
use $form->getErrorsAsString()
instead of $form->getErrors()
.
(which will run in to deep level including the form children.)
Upvotes: 1