How to use POST data from one model in another model

I want to use a single search box to search all the columns in my user table and display the results in a grid. The problem is that I do not know how to get the search post data to the search() method in the user model. I know there must be a simple answer to this problem.

View code:

<div class="search-form">

<div class="wide form">

<?php $form=$this->beginWidget('CActiveForm', array(



)); ?>

	<div class="row">

		<?php echo $form->textField($model_search,'search_string',array('size'=>60,'maxlength'=>128)); ?>


	<div class="row buttons">

		<?php echo CHtml::submitButton('Search'); ?>


<?php $this->endWidget(); ?>


</div><!-- search-form -->


    // Display the user grid from user model

    $this->widget('zii.widgets.grid.CGridView', array(











)); ?>

Search method in the user model. Notice the ??? where my problem is. What goes here?

public function search()


    // Warning: Please modify the following code to remove attributes that

    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('username',<img src='' class='bbc_emoticon' alt='???' />,true, 'OR');

    $criteria->compare('email',<img src='' class='bbc_emoticon' alt='???' />,true, 'OR');

    return new CActiveDataProvider($this, array(




You should replace your ??? with the [font=“Courier New”]name[/font] attribute of the desired input field.

In your example, that would be the name of the input generated by Yii for [font="Courier New"]$model_search[/font] (is that a typo?) for the [font="Courier New"]search_string[/font] attribute.

If it’s the same model, you can just use $model->attribute syntax, like the Gii generated code.

Of course, if it’s not an attribute of your current model, you have to declare it as a public variable, and to add it as well to the safe array in your model’s validation rules.

It is not the same model because $model is type ActiveRecord, and there is no attribute for search string. I am using a separate model $model_search for the search string. Is this what you recommend, or is there another way?

What exactly do you mean by "declare it as a public variable"? Where do I declare it as a public variable?

I ended up adding a virtual attribute to the model. I think that is what bennouna was suggesting.

Yes, a virtual attribute. I’m new to MVC :slight_smile: