3
votes

I need to store a record in First Model. It has around 10 fields. Now, I need to apply required rule for one field which i'm storing in SECOND model and I'm getting these values for this field from Third model.(it is a drop down field)

how can i make this field mandatory in yii??

can any one help please..

Many Thanks,

1
if you have a required rule in the 2nd model, and you are passing a 2nd model instance to the form, then it should all work - bool.dev
so i dont need to have required rule in present First model?? - Developer
it all depends on the field, from what i gather the field is from 2nd model, and not first, hence rule in 2nd model. if the field is in both models, then you would need the rule for both of them. - bool.dev
have you read this? - bool.dev

1 Answers

0
votes

You can add additional attributes and rules to a model. You don't have to only use attributes that directly relate to fields in your database table. Let's look at a basic example. You have a user (User) table which has the following fields:

  • id
  • email
  • password

And you have another table which stores user profile (UserProfile) information which has the structure:

  • id
  • user_id
  • country

When the user creates their account, you would have a form that captures their information. Your User model would have rules like:

array('email, password', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...

You can add an attribute for country to your User model like so:

class User extends CActiveRecord {
    public $country;
    ...

And then in your rules you can add the new attribute:

array('email, password, country', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...

The country attribute will now be a part of your User model. You can now add that to your form:

<?php echo $form->dropDownList($model,'country',CHtml::listData(Country::model()->findAll(),'id','country_name'),array('empty'=>'-- select a country --')); ?>

Now on your form submit, the $model->validate() method will validate the country field. You can save this manually to your second model (UserProfile), something like:

if(isset($_POST['User'])){
   if ($model->validate()){
       $user_profile = new UserProfile;
       $user_profile->user_id = $model->id;
       $user_profile->country = $model->country;
       $user_profile->save();
      ...

Hopefully that answers your question.