您必须创建自己的派生自CLinkPager 的类。最终,您要实现的是更改thaddeusmt mentions,CLinkPager::createPageButtons内部的行:
$buttons[]=$this->createPageButton($this->lastPageLabel /* the rest doesn't matter */);
相当于
$buttons[]=$this->createPageButton($pageCount /* the rest doesn't matter */);
显然,这样做的直接方法是覆盖createPageButtons,但这不是一个简单的方法,如果你完全覆盖它,你的寻呼机可能会与更高版本的 Yii 上的代码“不同步”。因此,让我们寻找替代方案。
替代方案
(如果您只对解决方案感兴趣,可以跳过此部分)
另一种方法是覆盖该方法,让它调用标准实现,然后简单地更改您需要更改的内容:
protected function createPageButtons() {
$buttons = parent::createPageButtons(); // Yii's implementation
array_pop($buttons); // remove last item, which is the link for the last page
$buttons[]=$this->createPageButton($this->getPageCount() /* the rest unchanged */);
return $buttons;
}
这更好,但它仍然涉及复制/粘贴代码,因此您的实现需要使该部分与未来的 Yii 版本保持同步。我们还能做得更好吗?事实证明是的。这是CLinkPager::run的方法:
public function run()
{
$this->registerClientScript();
$buttons=$this->createPageButtons();
if(empty($buttons))
return;
echo $this->header;
echo CHtml::tag('ul',$this->htmlOptions,implode("\n",$buttons));
echo $this->footer;
}
如您所见,CLinkPager 除了调用createPageButtons 之外并没有真正做很多事情。所以你可以覆盖run 并在让Yii 的代码运行之前动态设置$this->lastPageLabel 的值,如下所示:
public function run()
{
$this->lastPageLabel = $this->getPageCount();
parent::run();
}
嗯,这很好。我们通过仅覆盖一种方法并编写两行代码来实现目标。另外,如果CLinkPager 的实现在未来发生变化,我们的代码中没有任何内容需要与 Yii 保持同步。
另一方面,所有这些解决方案都引入了一个可能有问题的杂质:当有人编写使用我们的自定义分页器类的视图时,他们可能不知道我们实际上覆盖了该值的lastPageLabel!想象一下“为什么它不输出我告诉它的标签?”混乱。
一个非常好的解决方案
幸运的是,您可以像这样覆盖CLinkPager::init 来吃馅饼:
public function init()
{
// "Hijack" the default values for properties that the user did not set.
// This allows the user to still override this if they want to.
if($this->nextPageLabel===null)
$this->nextPageLabel='<';
if($this->prevPageLabel===null)
$this->prevPageLabel='>';
if($this->firstPageLabel===null)
$this->firstPageLabel='1';
if($this->lastPageLabel===null)
$this->lastPageLabel=$this->getPageCount();
// and let Yii do the rest like it always does
parent::init();
}
然后您可以配置您的视图以使用此寻呼机,一切都会顺利进行,无需多言:
'pager' => array('class' => 'CustomLinkPager'),