Required field for another model field in yii

I need to save the entry in the first model. It has about 10 fields. Now I need to apply the required rule for one field that I store in the SECOND model, and I get these values ​​for that field from the third model. (This box is down)

how can i make this field required in yii ??

can anyone help please.

Many thanks,

+3


source to share


1 answer


You can add additional attributes and rules to the model. You don't need to only use attributes that are directly related to fields in the database table. Let's look at a basic example. You have a custom (custom) table that has the following fields:

  • ID
  • Email
  • password

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

  • ID
  • user_id
  • Country

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

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

      

You can add a country attribute to your user model like this:

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

      



And then in your rules, you can add a new attribute:

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

      

The country attribute will now be part of your user model. Now you can add this to your form:

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

      

Now, when submitting the form, the method $model->validate()

will check the country field. You can save this manually into a second model (UserProfile), for example:

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();
      ...

      

Hope this answers your question.

0


source







All Articles