Unique Records

I am trying to implement unique records in the database table. The fields product_id and image_name should be unique as a combination - how do I specify a combination of fields to check on?

I also need to pass back an error message to the view (maybe using $model->addError)?

this should help you

http://www.yiiframework.com/doc/guide/form.model#declaring-validation-rules

OK I tried array(‘product_id, image_name’, ‘unique’)

But this seems to check each attribute seperately - I need it to check as a combination.

if one is unique, the combination is unique, too ;)

no man. for example - current data:

product_id | image_name

001 | flowers.jpg

input data:

001 | animals.jpg (this is OK)

002 | flowers.jpg (this is OK)

001 | flowers.jpg (this is not OK)




public function rules()

    {

        return array(

            array('image_name', 'checkCombination'),

        );

    }

 

    public function checkCombination($attribute,$params)

    {

        if(!$this->hasErrors())  // we only want to authenticate when no input errors

        {

            $product = Product::model()->find('product_id = ? AND image_name = ?', array($this->product_id, $this->image_name));

            if($product)

                $this->addError('image_name','Too Bad.');

        }

    }




cheers mbi - that kind of half works - it does not add the duplicate entry to the database but the error is not displayed on the page. I have put <?php echo CHtml::errorSummary($model); ?> on the page.

BUMP

$this->addError(‘image_name’,‘Too Bad.’);

also seems to be causing problem with updating the record.

Cause the rule




array('image_name', 'checkCombination')



applies for all the scenarios.

You can specify the ‘on’ to say in wich scenarios the rule must apply:




array('image_name', 'checkCombination', 'on'=>'insert')



Thanks PoL, but I still can’t get the error message to display on the page, any idea why?




//.. in your view

<?php echo CHtml::errorSummary($model); ?>



Sounds simple but has caught me out a few times…

I already got that bro, error message still does not display…

Sorry, just noticed you specified this in an eralier post…

Try verifying the model attributes are getting assigned e.g.




//..

$model->attributes = $_POST['TheForm'];

CVarDummper::dump($model->attributes);



Or go inside your custom validator and set some echo points to see if it is working.