0

I have a case where user can select multiple values in the list box and save it to the database using model.

Here is the table structure

user_id int(11) , cars_id int(5)

Here is the snippet of my view

<?php echo CHtml::dropDownList("sourceCars", '',CHtml::listData(MasterCars::model()->findAll(),'cars_code','car_name'),array('size'=>20) );?>

<?php echo CHtml::dropDownList("targetCars", '', array(),array('size'=>20) );?>

User selects the cars from sourceCars and moves into targetCars using Jquery ( This part is done) and clicks on Save or Submit button .

Now I should be able to save all the cars he/she selected in the targetCars list. Moreover in model I should put a condition that user can't save more than 10 cars and at least one car should be selected . Also user can select 5 cars at one time and next time when he comes he should be able to select max 5 cars only since he already save 10 records .

Could you please throw me some idea to implement this ? any Links that can guide me ?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Bujji
  • 1,717
  • 10
  • 41
  • 66

2 Answers2

1

your question is to limit selection of cars between 1-10. You need validate user input both client and server. At server,you can custom a ActiveRecord validation

public function rules()
{
    return array(
        array('cards_id', 'limitSelect','min'=>1,'max'=>10),
    );
}

public function limitSelect($attribute,$params)
{
         //and here your code to get the count of selection of cars for a user
         ...
        if($count<=$params['min'])
           $this->addError('cards_id','at least one car should be selected');
        if($count>=$params['max'])
            $this->addError('cards_id',' can't select more than 10 cars');
}



    //and for mutiple select you can code this:
echo CHtml::dropDownList("sourceCars", '',CHtml::listData(MasterCars::model()->findAll(),'cars_code','car_name'),array('size'=>20,'multiple'=>true) );
//anyway you can implement it in several way
user776067
  • 166
  • 5
  • thanks for your response @user776067 . I am doing validation at client level . But at server level I am looking for help and also for Multiple records insert ... The validation you gave me on top works for one time and next time if the user already have 9 cars in the database and he wants to add 10 more cars , I have to query database and have to get his values and have to validate ... – Bujji Aug 12 '11 at 09:55
  • using dao to insert the records – Bujji Aug 24 '11 at 11:18
0

Sounds like you want to use scenarios, see docs here. You can dynamically set the scenario with CModel::setScenario based on the user flow.

ldg
  • 9,112
  • 2
  • 29
  • 44