SortColumn.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-10-01 10:43
  7. */
  8. namespace backend\grid;
  9. use Closure;
  10. use yii\base\InvalidArgumentException;
  11. use yii\db\ActiveRecord;
  12. use yii\helpers\Html;
  13. use yii\helpers\Url;
  14. class SortColumn extends DataColumn
  15. {
  16. public $attribute = 'sort';
  17. public $options = ['style'=>'width:50px', 'class'=>'sort'];
  18. /**
  19. * @var string 在input onBlur时提交的地址,默认为当前控制器下的actionSort方法
  20. */
  21. public $action = null;
  22. /**
  23. * @var string 在input onBlur时ajax提交的方法
  24. */
  25. public $method = 'post';
  26. /**
  27. * @var array 主键
  28. */
  29. public $primaryKey = [];
  30. /**
  31. * @inheritdoc
  32. */
  33. public function init()
  34. {
  35. parent::init();
  36. if( !isset($this->options['class']) ){
  37. $this->options['class'] = 'sort';
  38. }else if(strpos($this->options['class'], 'sort') === false){
  39. $this->options['class'] .= ' sort';
  40. }
  41. $this->action === null && $this->action = Url::to(['sort']);
  42. $this->headerOptions = array_merge(['action'=>$this->action, 'method'=>$this->method, 'sort-header'=>1], $this->headerOptions);
  43. $this->content = function ($model, $key, $index, $gridView) {
  44. /* @var $model \backend\models\Article */
  45. $pk = [];
  46. if( !empty( $this->primaryKey ) ){
  47. if( $this->primaryKey instanceof Closure){
  48. $pk = call_user_func($this->primaryKey, $model);
  49. }else{
  50. $pk = $this->primaryKey;
  51. }
  52. if( !is_array($pk) ){
  53. throw new InvalidArgumentException("SortColumn primary key must be closure return array or config with array ( like ['id'=>1] )");
  54. }
  55. }else{
  56. if( is_object($model) && $model instanceof ActiveRecord ){
  57. $primaryKeys = $model->getPrimaryKey(true);
  58. foreach ($primaryKeys as $key => $abandon) {
  59. $pk[$key] = $model[$key];
  60. }
  61. }
  62. }
  63. if( empty($pk) ){
  64. throw new InvalidArgumentException("SortColumn must set table primary key or pass a primaryKey");
  65. }
  66. is_array($pk) && $pk = json_encode($pk);
  67. return Html::input('number', "{$this->attribute}[{$pk}]", $model[$this->attribute], $this->options);
  68. };
  69. }
  70. }