CheckboxColumn.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\grid;
  8. use Closure;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Html;
  11. /**
  12. * CheckboxColumn displays a column of checkboxes in a grid view.
  13. * Users may click on the checkboxes to select rows of the grid. The selected rows may be
  14. * obtained by calling the following JavaScript code:
  15. *
  16. * ~~~
  17. * var keys = $('#grid').yiiGridView('getSelectedRows');
  18. * // keys is an array consisting of the keys associated with the selected rows
  19. * ~~~
  20. *
  21. * @author Qiang Xue <[email protected]>
  22. * @since 2.0
  23. */
  24. class CheckboxColumn extends Column
  25. {
  26. public $name = 'selection';
  27. public $checkboxOptions = [];
  28. public $multiple = true;
  29. public function init()
  30. {
  31. parent::init();
  32. if (empty($this->name)) {
  33. throw new InvalidConfigException('The "name" property must be set.');
  34. }
  35. if (substr($this->name, -2) !== '[]') {
  36. $this->name .= '[]';
  37. }
  38. }
  39. /**
  40. * Renders the header cell content.
  41. * The default implementation simply renders [[header]].
  42. * This method may be overridden to customize the rendering of the header cell.
  43. * @return string the rendering result
  44. */
  45. protected function renderHeaderCellContent()
  46. {
  47. $name = rtrim($this->name, '[]') . '_all';
  48. $id = $this->grid->options['id'];
  49. $options = json_encode([
  50. 'name' => $this->name,
  51. 'multiple' => $this->multiple,
  52. 'checkAll' => $name,
  53. ]);
  54. $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);");
  55. if ($this->header !== null || !$this->multiple) {
  56. return parent::renderHeaderCellContent();
  57. } else {
  58. return Html::checkBox($name, false, ['class' => 'select-on-check-all']);
  59. }
  60. }
  61. /**
  62. * @inheritdoc
  63. */
  64. protected function renderDataCellContent($model, $key, $index)
  65. {
  66. if ($this->checkboxOptions instanceof Closure) {
  67. $options = call_user_func($this->checkboxOptions, $model, $key, $index, $this);
  68. } else {
  69. $options = $this->checkboxOptions;
  70. if (!isset($options['value'])) {
  71. $options['value'] = is_array($key) ? json_encode($key) : $key;
  72. }
  73. }
  74. return Html::checkbox($this->name, !empty($options['checked']), $options);
  75. }
  76. }