Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active March 10, 2017 11:32
Show Gist options
  • Save jamband/1433055 to your computer and use it in GitHub Desktop.
Save jamband/1433055 to your computer and use it in GitHub Desktop.
Yii Framework: pagination and searching
<?php
class Hoge extends CActiveRecord
{
...
/**
* Gets the all models.
* @param string $q
* @return array
*/
public function getAll($q)
{
$c = new CDbCriteria;
$c->addSearchCondition('t.fuga', $q);
$c->order = 't.id DESC';
$pages = new CPagination($this->count($c));
$pages->pageSize = 5;
$pages->applyLimit($c);
$pages->params = $q ? compact('q') : null;
return array(
$pages,
$this->findAll($c),
);
}
}
<?php
class HogeController extends Controller
{
/**
* Lists all models.
*/
public function actionIndex()
{
$q = trim(mb_convert_kana(Yii::app()->request->getParam('q'), 's', 'UTF-8');
list($pages, $models) = Hoge::model()->getAll($q);
$this->render('index', compact('q', 'pages', 'models'));
}
<div class="form">
<?php echo CHtml::form($this->createUrl($this->route)); ?>
<div class="row">
キーワード検索<br />
( 入力後「Enterキー」を押してください )<br />
<?php echo CHtml::textField('q', $q); ?>
</div><!-- /.row -->
<?php echo CHtml::endForm(); ?>
</div><!-- /.form -->
<?php $this->widget('CLinkPager', compact('pages')); ?>
<?php echo CHtml::encode('結果数: ' . $pages->itemCount . '件'); ?>
<?php foreach ($models as $model): ?>
<div class="view">
<?php echo CHtml::encode($model->fuga); ?>
<?php echo CHtml::encode($model->piyo); ?>
</div><!-- /.new -->
<?php endforeach; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment