问题
I'm new to Symfony Framework and I ran into a problem with form validation.
I want to update data in DB including unique column, but if unique column is unchanged, an error is returned (An object with the same "domain" already exist."). Domain column must be unique, but user should be able to change it. So, if one user saves his domain name, no one else can use it, but he can change it in future.
It seems like form validation compares unique column not only to other rows, but to itself too. So if user don't change the column and saves form, error is returned.
What validation should I use to preserve column unique, but free to change?
回答1:
If you are using Doctrine and the validator is sfValidatorDoctrineUnique, it should work as intended.
i.e validates if you are updating an object. See line 102.
回答2:
This may be an old question, but I'll add further details on the cause of this error since I also encountered the problem and found a solution.
In my case, the Validator did not return true for the isUpdate() method, this was because the 'id' field was unset.
To avoid this problem, remove the 'id' from the unset fields and change it to a sfWidgetFormInputHidden.
回答3:
to make isUpdate() you have to use $this->form->setPostValidator();
$this->validatorSchema->setPostValidator( new sfValidatorDoctrineUnique(array('model' => 'Model', 'column' => 'column_name')) );
回答4:
You are partly right, but the problem is, if someone want to change other field, while unique, stay the same, then the problem remains. I don't see any way to prevent this, apart from do it by yourself :/
回答5:
You should use merge
instead of persist
For Example:
$entityManager = $this->getDoctrine()->getManager();
$loadedBrand = $entityManager->merge($loadedBrand);
$entityManager->flush();
来源:https://stackoverflow.com/questions/3166127/symfony-updating-unique-column-validation-problem