Exist Validator Not Working Correctly In Yii 1.1.13

Hello, recently I upgraded to Yii 1.1.13. I have not been able to use the ‘exist’ validator since. I have not had issues in the past. What is strange is that even if the user exists, I receive a validation error saying the ‘id’ is invalid. If I manually create the first record and type the user id in, it works fine. I can create subsequent entries after I manually created the first record. I hope that makes sense.

I basically have one user in the database for this example. When I create a new record in the record table manually it works fine and passes subsequent validations. If I keep the user as it is, and remove all entries from the record table, it fails validation, even though the user exists. Here is my example:




--

-- Table structure for table `record`

--


CREATE TABLE IF NOT EXISTS `record` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `record_name` varchar(25) CHARACTER SET latin1 NOT NULL,

  `user_id` int(10) unsigned NOT NULL,

  PRIMARY KEY (`id`),

  KEY `user_id` (`user_id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;





--

-- Table structure for table `user`

--


CREATE TABLE IF NOT EXISTS `user` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(25) CHARACTER SET latin1 NOT NULL,

  `email` varchar(25) CHARACTER SET latin1 NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;




--

-- Constraints for table `record`

--

ALTER TABLE `record`

  ADD CONSTRAINT `record_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;






// For the Record Model


public function rules()

{

    return array(

        array('record_name, user_id', 'required'),

	array('record_name', 'length', 'max'=>25),

	array('user_id', 'exist'),

	array('id, record_name, user_id', 'safe', 'on'=>'search'),

    );

}


public function relations()

{

    return array(

        'user' => array(self::BELONGS_TO, 'User', 'user_id'),

    );

}






// For the User Model


public function rules()

{

    return array(

        array('name, email', 'required'),

	array('name, email', 'length', 'max'=>25),

	array('id, name, email', 'safe', 'on'=>'search'),

    );

}


public function relations()

{

    return array(

        'records' => array(self::HAS_MANY, 'Record', 'user_id'),

    );

}



You did not set the className - http://www.yiiframework.com/doc/api/1.1/CExistValidator#className-detail

Without that the validator checks if the user_id exists in the Record table instead of the User table

Thank you! I can’t believe I overlooked that. I have the Yii validator cheatsheet right in front of me. I changed the line to:


array('user_id', 'exist', 'attributeName'=>'id', 'className'=>'User', 'allowEmpty'=>false)

That seems to work. Thanks again!