FOSRestBundle How to validate the registration?

心已入冬 提交于 2019-12-09 23:29:27

问题


I'm developing a RESTFul API in Symfony 2.3.* with FOSUserBundle and FOSRestBundle, and I'm having trouble understanding how to create a registration method.

My controller look like this :

class UserRestController extends FOSRestController
{
    //Other Methods ...

    public function postUserAction()
    {
        $userManager = $this->get('fos_user.user_manager');
        $user = $userManager->createUser();

        $param = $paramFetcher->all();
        $form = $this->createForm(new UserType(), $user);
        $form->bind($param);

        if ($form->isValid() == false)
            return $this->view($form, 400);

        $userManager->updateUser($user);
        return $this->view('User Created', 201);
    }

    //...
}

And my UserType class :

class UserType extends BaseType
{
    public function __construct($class = "User")
    {
        parent::__construct($class);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('username', 'username')
                ->add('email', 'email')
                ->add('plainPassword', 'repeated', array(
                   'first_name' => 'password',
                   'second_name' => 'confirm',
                   'type' => 'password'
                ))
                ->add('lastname')
                ->add('firstname')
                ->add('job_position')
                ->add('phone')
                ->add('company_name')
                ->add('website')
                ->add('sector')
                ->add('address')
                ->add('city')
                ->add('zip_code')
                ->add('country')
                ->add('billing_infos_same_as_company')
                ->add('billing_address')
                ->add('billing_city')
                ->add('billing_zip')
                ->add('billing_country')
                ->add('putf')
                ->add('das');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Wipsea\UserBundle\Entity\User',
            'csrf_protection' => false
        ));
    }

    public function getName()
    {
        return 'wipsea_user_registration';
    }
}

When I test it, no matter what the form isn't valid and shows no error. And when I try to get the request :

"Validation Failed" "This form should not contain extra fields."

Is there a way to properly validate the form ?

EDIT : Updating my problem.


回答1:


I would recommend you this tutorial in 3 parts - there is everything you need:

  • http://welcometothebundle.com/symfony2-rest-api-the-best-2013-way/
  • http://welcometothebundle.com/web-api-rest-with-symfony2-the-best-way-the-post-method/
  • http://welcometothebundle.com/symfony2-rest-api-the-best-way-part-3/

If you want to provide complex user validation you should create UserType form and pass data to this form instead of directly setting all properties:

public function postAction()
{
    $user = new User();

    $form = $this->createForm(new UserType(), $user);
    $form->handleRequest($this->getRequest());

    if ($form->isValid()) {
        // propel version
        $user->save();

        $response = new Response();
        $response->setStatusCode(201);

        // set the `Location` header only when creating new resources
        $response->headers->set('Location',
            $this->generateUrl(
                'acme_demo_user_get', array('id' => $user->getId()),
                true // absolute
            )
        );

        return $response;
    }

    // return form validation errors
    return View::create($form, 400);
}

In part 2 of this tutorial you have all information about creating form, passing data and validating it with RestBundle.

There is also a lot information about best practices using REST with Symfony2.




回答2:


Take a look at this code:

https://github.com/piotrjura/fitness-api/blob/master/src/Fitness/FitnessBundle/Service/UsersService.php#L40

https://github.com/piotrjura/fitness-api/blob/master/src/Fitness/FitnessBundle/Controller/UsersController.php#L30

Also check validation.yml and entity serializer yml files.

You don't need forms to do the validation. And you definitly should not put the user creation and validation logic inside a controller. In case you'd like to make use of that form anyway later, eg. render it on the backend side, you'll have to write the same code twice.




回答3:


I had to have the getName() method return '' in order for it to work for me.

https://github.com/FriendsOfSymfony/FOSRestBundle/issues/585



来源:https://stackoverflow.com/questions/25509486/fosrestbundle-how-to-validate-the-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!