duplicate entry when function beforeValidate

i have this table (using sqlserver 2012)




CREATE TABLE [dbo].[CustomerTransactions](

	[TransactionNumber] [nvarchar](11) NOT NULL,

	[TransactionDate] [date] NOT NULL,

	[SLoc] [nvarchar](4) NOT NULL,

	[CustId] [nvarchar](10) NOT NULL,

	[IsProcessed] [bit] NOT NULL,

	[IsCancelled] [bit] NOT NULL,

 CONSTRAINT [PK_CustomerTransactions] PRIMARY KEY CLUSTERED 

(

	[TransactionNumber] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]


GO



and this my function before validate




 protected function beforeValidate() {

        parent::beforeValidate();

        if ($this->isNewRecord) {

            $criteria = new CDbCriteria;

            $criteria->select = 'TransactionNumber';

            $criteria->limit = 10;

            $criteria->order = 'TransactionNumber DESC';

           $criteria->condition = 'LEFT( TransactionNumber, 5) =  CONVERT(VARCHAR(5),GETDATE(),5)';

            $last = $this->find($criteria);

            if ($last) {

                $nomorId = (int) substr($last->TransactionNumber, 5) + 1;

                $nomorId = date('ymd') . '' . sprintf("%05d", $nomorId);

            } else {

                $nomorId = date('ymd') . '' . sprintf("%05d", 1);

            }

            $this->TransactionNumber = $nomorId;

        }

        return true;

    }




i always get duplicate entry

anybody can help me??

maybe because you should use beforeSave instead of beforeValidate? When you call $model->save(), a validation is performed automatically.

no sir. i have try




public function beforeSave() {

        if ($this->isNewRecord) {

            $criteria = new CDbCriteria;

            $criteria->select = 'TransactionNumber';

            $criteria->limit = 10;

            $criteria->condition = 'LEFT(TransactionNumber, 6) =  CONVERT(varchar(6), GETDATE(), 12)';

            $criteria->order = 'TransactionNumber DESC';

            $last = $this->find($criteria);

            if ($last) {

                $nomorId = (int) substr($last->TransactionNumber, 6) + 1;

                $nomorId = date('ymd') . '' . sprintf("%06d", $nomorId);

            } else {

                $nomorId = date('ymd') . '' . sprintf("%06d", 1);

            }

            $this->TransactionNumber = $nomorId;

        }

        return parent::beforeSave();

    }



i didn’t get duplicate entry, but transactionNumber can not return back to first number when changed date

example today 2015-12-25 generate number = 15122500001 until 15122500020

but when i change date to 2015-12-26 generate number to be 15122600021

i want to be 15122600001 when date 2015-12-26.

can you help me sir. thanks before

where is your controller#action code. I think beforeValidation() is okay