Trainee
Trainee

Reputation: 15

Yii not allowing to insert same data

I'm using yii framework. I have made a condition where users are not allowed to insert a same data.

here is my code

model

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('DEP_CD', 'length', 'max'=>5),
        array('DEP_CD', 'required'),
        array('DEP_CD', 'cekPK'),
    );
}

public function cekPK()
{
    $model = self::findByPk(array($this->DEP_CD));
    if ($model)
        $this->addError('field1', 'Data sudah ada');
}

this code works for not allowing user to insert a same data. but when they edit/update the data, it keep saying that data is exist. I need to make users allowed to edit but not inserting the same data only

thanks

Upvotes: 0

Views: 55

Answers (1)

Paul
Paul

Reputation: 1657

A work around could be:

public function cekPK()
{
    if ($this->isNewRecord)
    {
        $model = self::findByPk(array($this->DEP_CD));
        if ($model)
            $this->addError('field1', 'Data sudah ada');
    }
}

Upvotes: 1

Related Questions