i used phalcon framework to build rest api .. i was built all CRUD functions but when using update i can't update record because validation failed because email is unique .. i want to update this record with skip the unique validation .. this is my validation :
class UpdateUserValidation extends Validation
{
public function initialize()
{
$this->add(
'email',
new Uniqueness([
"model" => new Users,
"message" => ": email already exist",
]));
}}
and this is my function in controller :
public function updateAction($id)
{
$validation = new UpdateUserValidation;
$messages = $validation->validate($_POST);
if (count($messages) > 0 ) {
$all_errors = array();
foreach ($messages as $message) {
array_push($all_errors, $message->getMessage());
}
$this->response->setStatusCode(422,'Validation Error');
$this->response->setJsonContent(array('Message' => $all_errors));
return $this->response;
}
any help please
Phalcon DevTools (3.4.0)
PHP 7.1
It's not really well documented, but if you use the current row instance (model) for the validation, that record will be ignored.
// get record
$user = Users::findFirst([
'email = :email:',
'bind' => [
'email' => 'info@test.com',
],
]);
// validation
$this->add('email', new Uniqueness([
'model' => $user,
'message' => ':email already exist',
]));
$messages = $this->validate([
'email' => 'info@test.com',
]);
// success, because added current record
$messages = $this->validate([
'email' => 'existing@email.com',
]);
// fails, a record with this email already exists
// save
if(!$messages) {
$user->save([
'email' => 'info@test.com',
]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.