You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2KB

  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. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class LinkSorter extends Widget
  22. {
  23. /**
  24. * @var Sort the sort definition
  25. */
  26. public $sort;
  27. /**
  28. * @var array list of the attributes that support sorting. If not set, it will be determined
  29. * using [[Sort::attributes]].
  30. */
  31. public $attributes;
  32. /**
  33. * @var array HTML attributes for the sorter container tag.
  34. * @see \yii\helpers\Html::ul() for special attributes.
  35. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  36. */
  37. public $options = ['class' => 'sorter'];
  38. /**
  39. * @var array HTML attributes for the link in a sorter container tag which are passed to [[Sort::link()]].
  40. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  41. * @since 2.0.6
  42. */
  43. public $linkOptions = [];
  44. /**
  45. * Initializes the sorter.
  46. */
  47. public function init()
  48. {
  49. if ($this->sort === null) {
  50. throw new InvalidConfigException('The "sort" property must be set.');
  51. }
  52. }
  53. /**
  54. * Executes the widget.
  55. * This method renders the sort links.
  56. */
  57. public function run()
  58. {
  59. echo $this->renderSortLinks();
  60. }
  61. /**
  62. * Renders the sort links.
  63. * @return string the rendering result
  64. */
  65. protected function renderSortLinks()
  66. {
  67. $attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
  68. $links = [];
  69. foreach ($attributes as $name) {
  70. $links[] = $this->sort->link($name, $this->linkOptions);
  71. }
  72. return Html::ul($links, array_merge($this->options, ['encode' => false]));
  73. }
  74. }