LinkSorter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\Widget;
  11. use yii\data\Sort;
  12. use yii\helpers\Html;
  13. /**
  14. * LinkSorter renders a list of sort links for the given sort definition.
  15. *
  16. * LinkSorter will generate a hyperlink for every attribute declared in [[sort]].
  17. *
  18. * For more details and usage information on LinkSorter, see the [guide article on sorting](guide:output-sorting).
  19. *
  20. * @author Qiang Xue <qiang.xue@gmail.com>
  21. * @since 2.0
  22. */
  23. class LinkSorter extends Widget
  24. {
  25. /**
  26. * @var Sort the sort definition
  27. */
  28. public $sort;
  29. /**
  30. * @var array list of the attributes that support sorting. If not set, it will be determined
  31. * using [[Sort::attributes]].
  32. */
  33. public $attributes;
  34. /**
  35. * @var array HTML attributes for the sorter container tag.
  36. * @see \yii\helpers\Html::ul() for special attributes.
  37. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  38. */
  39. public $options = ['class' => 'sorter'];
  40. /**
  41. * @var array HTML attributes for the link in a sorter container tag which are passed to [[Sort::link()]].
  42. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  43. * @since 2.0.6
  44. */
  45. public $linkOptions = [];
  46. /**
  47. * Initializes the sorter.
  48. */
  49. public function init()
  50. {
  51. parent::init();
  52. if ($this->sort === null) {
  53. throw new InvalidConfigException('The "sort" property must be set.');
  54. }
  55. }
  56. /**
  57. * Executes the widget.
  58. * This method renders the sort links.
  59. */
  60. public function run()
  61. {
  62. echo $this->renderSortLinks();
  63. }
  64. /**
  65. * Renders the sort links.
  66. * @return string the rendering result
  67. */
  68. protected function renderSortLinks()
  69. {
  70. $attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
  71. $links = [];
  72. foreach ($attributes as $name) {
  73. $links[] = $this->sort->link($name, $this->linkOptions);
  74. }
  75. return Html::ul($links, array_merge($this->options, ['encode' => false]));
  76. }
  77. }