Ernesto Pulgaron
Ernesto Pulgaron

Reputation: 23

Integrity constraint exception handling with user friendly message Yii2

I have a table with a triple key, now I want to show a "friendly" warning if I repeat the key combination instead of this:

Integrity constraint violation – yii\db\IntegrityException SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'CP MEIJ 01/15-2' for key 'PRIMARY' The SQL being executed was: INSERT INTO modelo03 (planificacion_fk, cargo_fk, medida_apl_fk, modelo03_cant, dic_fk) VALUES ('CP MEIJ 01/15', 3, 2, 4, 'SA')

Error Info: Array ( [0] => 23000 [1] => 1062 [2] => Duplicate entry 'CP MEIJ 01/15-2' for key 'PRIMARY' )

Caused by: PDOException SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'CP MEIJ 01/15-2' for key 'PRIMARY'

in C:\wamp\www\prueba_protected\vendor\yiisoft\yii2\db\Command.php at line 768

as would be the way to achieve this? sorry for my english

Upvotes: 2

Views: 1814

Answers (2)

Liauchuk Ivan
Liauchuk Ivan

Reputation: 1993

If you use Model(ActiveRecord is subclass of the Model class) to insert this data to the database, you can use UniqueValidator.

In this case model will not be saved, and you can get list of errors using $model->errors.

You can configure validator to use you own error message.

Upvotes: 1

tnchalise
tnchalise

Reputation: 1583

Stop inserting same planificacion_fk for new entries. The error says, you are inserting a same primary key value which must be unique for all entries.

Upvotes: 0

Related Questions