Is it possible to use Yii’s DAO and still have have Yii validate database fields that are declared as unique?
For example, consider a database table called “user” that has a user_id, user_name, and user_password. The user_name has to be unique. When using Yii’s Active Record declaring user_name as unique in the model’s rules like so:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('user_name, user_password', 'required'),
array('user_name', 'unique'),
);
and displaying the user_name text fields in a view like so:
<div class="wide form">
<?php echo $form->labelEx($model,'user_name'); ?>
<?php echo $form->textField($model,'user_name'); ?>
<?php echo $form->error($model,'user_name'); ?>
</div>
will automatically validate the user_name attribute and report an error if the user enters a user_name that already exists in the user table.
Is it possible to achieve the same thing when using Yii’s DAO?
A second question: if using DAO, where should the DAO code be placed? For example, referring to the "user" example above, if I want to be able to add users, should I create something like addUser($user_name, $user_password) in the model, like so:
<?
class UserForm extends CFormModel
{
public $user_name;
public $user_password;
public function rules()
{
return array(
array('user_name, user_password', 'required'),
//array('user_name', 'unique'),
array('user_password', 'length', 'min'=>8, 'max'=>32),
);
}
public function addUser($user_name, $user_password)
{
$connection = Yii::app()->db;
$command = $connection->createCommand("CALL sp_CreateUser('$user_name', '$user_password')");
$command->execute();
}
}
and then call this from the controller?
Any help would be really appreciated.