问题
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