I have a model call ArticleCategory, I have slug field must be unique. I set keepSnapshot equal true. Here is my EditForm init code (Edit form of 1 category):
public function initialize(ArticleCategory $category) {
// Slug
$slug = (new Text('slug', [
'class' => 'form-control',
'placeholder' => 'Slug'
]))->addValidator(new PresenceOf([
'message' => 'Slug is required'
]));
if($category->hasChanged('slug')){
$slug->addValidator(new Uniqueness([
'message' => 'Slug exists',
'field' => 'slug',
'model' => 'App\Models\Entities\ArticleCategory'
]));
}
$slug->addFilter('trim');
$this->add($slug);
// other element
}
Controller code:
public function editAction($id) {
// Get article category by id
$articleCategory = $this->_articleCategoryService->getById($id);
if (!$articleCategory) {
return $this->show404();
}
$editForm = new EditForm($articleCategory);
// Post
if ($this->request->isPost()) {
$postData = $this->request->getPost();
if (!$editForm->isValid($postData)) {
$editForm->setDefaultsFromObject($articleCategory);
} else {
// Form valid
$editForm->bind($postData, $articleCategory);
if ($articleCategory->save()) {
$this->flash->success("Save success.");
return $this->redirectToIndex();
} else {
$this->flash->error("Save fail");
}
}
}
$this->view->editForm = $editForm;
}
I try to change slug with an slug that exist in db, the category alway save success, not validate unique because the hasChanged return false. My question: How can I add uniqueness validator in EditForm class when slug field change ??? Thank alot !