Validation in custom operation controller

て烟熏妆下的殇ゞ 提交于 2020-04-30 06:49:06

问题


I'm trying to do a validation only on a custom operation on api platform but it doesn't work.

I would like to change the password only if there is no error in the validation but in any case the password is changed.

If I remove the validation groups from the validation annotations it works.

for example if i replace @Assert\NotBlank(groups={"put-reset-password"}) with @Assert\NotBlank the validation pass.

This is the code of the entity :

  "CHANGE-PASSWORD"={
    "method"="PUT",
     "path"="/users/change-password/{id}",
     controller"="App\Controller\ChangePasswordController",
     "access_control"="is_granted('EDIT-PASSWORD', previous_object) and object == user",
     "openapi_context"={
        "summary"="Change Password"
     },
     "denormalization_context"={
        "groups"={"put-reset-password"}
     },
     "validation_groups"={"put-reset-password"},
  },

and here is my controller

public function __invoke(User $data)
{

    // Validate data and handle validation errors
    $this->validator->validate($data);

    $data->setPassword($this->userPasswordEncoder->encodePassword($data, $data->getNewPassword()));


    $this->entityManager->flush();
    $token = $this->tokenManager->create($data);


    return $data;
}

and here is one of my attributes in which i use validation group.

/**
 * @Groups({"put-reset-password"})
 * @Assert\NotBlank(groups={"put-reset-password"})
 * @UserPassword(groups={"put-reset-password"})
 */
private $oldPassword;

Any issue please ?


回答1:


This is strange behavior. You get null probably because you use interface

use ApiPlatform\Core\Validator\ValidatorInterface;

If use inface use Symfony\Component\Validator\Validator\ValidatorInterface you must be get object ConstraintViolationListInterface.

I have a similar problem. The following solution helped me:

/**
 * @Groups({"put-reset-password"})
 * @Assert\NotBlank(groups={"Default", "put-reset-password"})
 * @UserPassword(groups={"put-reset-password"})
 */
private $oldPassword;

It's strange, but after added "Default" my validation is worked in my custom operation.

Useful links:

https://symfony.com/doc/current/validation/groups.html https://symfony.com/doc/current/validation/sequence_provider.html

P.S. Sorry for my bad english.



来源:https://stackoverflow.com/questions/59533789/validation-in-custom-operation-controller

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