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.

77 lines
1.9KB

  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. * Initializes the sorter.
  40. */
  41. public function init()
  42. {
  43. if ($this->sort === null) {
  44. throw new InvalidConfigException('The "sort" property must be set.');
  45. }
  46. }
  47. /**
  48. * Executes the widget.
  49. * This method renders the sort links.
  50. */
  51. public function run()
  52. {
  53. echo $this->renderSortLinks();
  54. }
  55. /**
  56. * Renders the sort links.
  57. * @return string the rendering result
  58. */
  59. protected function renderSortLinks()
  60. {
  61. $attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
  62. $links = [];
  63. foreach ($attributes as $name) {
  64. $links[] = $this->sort->link($name);
  65. }
  66. return Html::ul($links, array_merge($this->options, ['encode' => false]));
  67. }
  68. }