Vit Kos
Vit Kos

Reputation: 5755

Yii Advanced and inline search via alias

I have several models with relations and what I am trying to do is to search the fields with the aliases I provide in DetailView. It looks like this

<?php $this->widget('bootstrap.widgets.BootGridView',array(
    'id'=>'operations-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'operationType.name:raw:Operation',
        'creation_date:datetime',
        'modification_date:datetime',
        'ammount_usd:raw:Ammount',
        'currency.short',
        /*

        'client_id',
        'organization_id',
        */
        array(
            'class'=>'bootstrap.widgets.BootButtonColumn',
        ),
    ),
)); ?>

And what I want is to be able to search through rows using the aliases for columns like currency.short. What is a correct approach to do that? Tried to modify the search() method like this..but I think I'm missing something.

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('creation_date',$this->creation_date,true);
    $criteria->compare('modification_date',$this->modification_date,true);
    $criteria->compare('ammount',$this->ammount,true);
    $criteria->compare('ammount_usd',$this->ammount_usd,true);
    $criteria->compare('currency_id',$this->currency_id);
    $criteria->compare('operation_type',operationType::model()->name);
    $criteria->compare('client_id',$this->client_id);
    $criteria->compare('organization_id',$this->organization_id);
$criteria->compare('comment',$this->comment);
    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

Thanks.

Upvotes: 1

Views: 669

Answers (1)

Johnatan
Johnatan

Reputation: 1268

You have to create a virtual field for that property. For example in your main model:

private _currencyshort = null;
public function setCurrencyshort($value) {
    $this->_currencyshort = $value;
}
public function getCurrencyshort() {
    if ($this->_currencyshort === null && $this->currency != null)
    {
        $this->_currencyshort = $this->currency->short
    }
    return $this->_currencyshort;
}
public function search() {
    $criteria=new CDbCriteria;
    $criteria->with = array('currency'); // add more elements to array if you want to search by more relations
    $criteria->compare('currency.short',$this->currencyshort);
    // You can also add this field to your sorting criteria
    // ... etc
}

Also you have to add currencyshort into your rules() method of main model to the line where it states 'on'=>'search', for example:

array('currencyshort', 'safe', 'on'=>'search'),

Then in columns instead of currency.short you can put currencyshort and it will work with filters, sorting and etc.

Upvotes: 3

Related Questions