Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form validation does not show error messages #1018

Closed
marcoshoya opened this issue Apr 15, 2015 · 7 comments
Closed

Form validation does not show error messages #1018

marcoshoya opened this issue Apr 15, 2015 · 7 comments

Comments

@marcoshoya
Copy link

Hi guys,

I'm trying submit a form to my controller but I can not get those errors messages from form.

According to docs (http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views), I should get

{
  "code": 400,
  "message": "Validation Failed";
  "errors": {
    "children": {
      "username": {
        "errors": [
          "This value should not be blank."
        ]
      }
    }
  }

However, my response is:

{
  "children": {
    "username": [],
  }
}

My config.yml

fos_rest:
    disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY
    param_fetcher_listener: true
    # formato default caso não seja informado
    routing_loader:
        default_format: json
    view:
        # registra os mimi types permitidos no header da request
        mime_types: 
            json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1']
        view_response_listener: 'force'
        formats:
            xml:  true
            json: true
        templating_formats:
            html: true
    format_listener: true
    exception:
        codes:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
        messages:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
    allowed_methods_listener: true
    access_denied_listener:
        json: true
    body_listener: true

My controller:

<?php

namespace AppBundle\Controller;

use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

class SecurityController extends FOSRestController
{

    /**
     * Auth
     *
     * @ApiDoc(
     *  resource=true,
     *  description="Do the authentication",
     *  parameters={
     *      {"name"="username", "dataType"="string", "required"=true, "description"="username from user"}
     *  },
     *  statusCodes={
     *      200="Returned when successful"
     *  }
     * )
     *
     * @Rest\Post()
     * @Rest\View()
     */
    public function authAction(Request $request)
    {
        $form = $this->createFormBuilder()
                ->add('username', 'text', array('constraints' => new Assert\NotBlank()))
                ->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            // do something
        }

        return $form;

    }

}

What I am doing wrong???

Thanks in advance

@marcoshoya
Copy link
Author

Update: I've tried the solution here (#738 (comment)) and It's works.

I also tried

$form->submit(array(
            'username' => $request->get('username')
        )); 

Anyway, I guess it must be a better way to validate input data...

Thanks

@ghost
Copy link

ghost commented Apr 28, 2015

I had same issue. But it's strange as official symfony documentation suggest only using handleRequest() method because submit() is deprecated. http://symfony.com/doc/current/cookbook/form/direct_submit.html#cookbook-form-call-submit-directly

@Davidmattei
Copy link

@sepikas-antanas : I think using the request object as a input parameter for the submit function is deprecated, not the function itself ?

@GuilhemN
Copy link
Member

Do you use the jmsserializer or the symfony serializer?

And submit is not deprecated as @sepikas-antanas said only passing Request as an attribute.

@Kaz-
Copy link

Kaz- commented Aug 8, 2016

I got exactly the same issue and I'm using jmsserializer, any idea of where it might come from ?

@manasbala
Copy link

manasbala commented Aug 12, 2016

You should return

$view = $this->view($form->getErrors(true));
return $this->handleView($view);

@pguso
Copy link

pguso commented Dec 22, 2017

i solved it like this:

    $user = new User;
    $form = $this->createForm(UserType::class, $user);
    $view = View::create();

    $form->submit($request->request->all());
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($user);
        $em->flush();

        $view->setData($form->getData());
    } else {
        $view->setData($form);
    }

    return $this->handleView($view);

Don't forget to disable CSRF validation (https://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#csrf-validation)

fos_rest:
    disable_csrf_role: ROLE_API
    #disable_csrf_role: IS_AUTHENTICATED_ANONYMOUSLY #just for testing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants