在yii中对自定义列Fullname应用排序和搜索

时间:2015-04-09 07:03:52

标签: php model-view-controller yii2

我有一个tbl人,它有id,first_name,last_name.Now在YII中使用getter我创建了一个函数getFullName,显示first_name + last_name..it工作正常,但是它显示了full name列in​​ without sorting选项where first_name和last_name默认拥有它。 我以前在YII没有任何经验。如何将全名列排序? 感谢

模型:人     

namespace app\models;

use Yii;

/**
 * This is the model class for table "person".
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name

 */
class Person extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'person';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['first_name', 'last_name'], 'required'],
            [['first_name', 'last_name'], 'string', 'max' => 100],
            [['fullName'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'first_name' => Yii::t('app', 'First Name'),
            'last_name' => Yii::t('app', 'Last Name'),
            'fullName' => Yii::t('app', 'Full Name')

        ];
    }

   public function getFullName()
   {
      return $this->first_name . " " . $this->last_name;
   }

}

查看人:index.php

    <?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\filters\VerbFilter;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'People');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="person-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Create Person'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'first_name',
            'last_name',
            'fullName',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

</div>

1 个答案:

答案 0 :(得分:0)

1)您的模型类人员中的Delcare public $fullname;

2)在你的Person Model类search method中添加以下行(我使用yii语法,请将其转换为yii2语法),

    $criteria=new CDbCriteria;
    $criteria->select = " *, CONCAT_WS(' ', first_name, last_name) as fullname";
    $criteria->compare('fullName',$this->fullName);
    ..........
   // your compare code goes here
    ......... 
    $sort = new CSort();
    $sort->attributes = array(
        'fullName'=>array(
            'asc'=>'fullName ASC',
            'desc'=>'fullName DESC',
        ),
        '*', 
    );

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'sort'=>$sort,
    ));