Advertisement
Guest User

Untitled

a guest
Oct 9th, 2012
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 23.88 KB | None | 0 0
  1. <?php
  2.  
  3. namespace lib\Cs;
  4.  
  5. class jqGrid
  6. {
  7.     private $_id = 0;
  8.     private $_where_rules = array(
  9.         'eq'=>" = ",
  10.         'ne'=>" <> ",
  11.         'lt'=>" < ",
  12.         'le'=>" <= ",
  13.         'gt'=>" > ",
  14.         'ge'=>" >= ",
  15.         'bw'=>" LIKE ",
  16.         'bn'=>" NOT LIKE ",
  17.         'in'=>" IN ",
  18.         'ni'=>" NOT IN ",
  19.         'ew'=>" LIKE ",
  20.         'en'=>" NOT LIKE ",
  21.         'cn'=>" LIKE ",
  22.         'nc'=>" NOT LIKE ",
  23.         'nu'=>" IS NULL",
  24.         'un'=>" IS NOT NULL",
  25.         );
  26.    
  27.     private $_options = array(
  28.         'caption' => null,
  29.         'datatype' => 'local',
  30.         'rowNum' => 50,
  31.         'width' => 900,
  32.         'height' => 300,
  33.         'rowList' => array(10,20,30,50),
  34.         'viewrecords' => true,
  35.         'scrollrows' => true,
  36.         'url' => '',
  37.         'editurl' => '',
  38.         'scroll' => 0,
  39.         'sortable' => true,
  40.         'multiselect' => true,
  41.         "jsonReader" => array("repeatitems" => false)
  42.     );
  43.     private $_actions = array(
  44.         'view' => false,
  45.         'edit' => false,
  46.         'add' => true,
  47.         'del' => false,
  48.         'search' => false,
  49.         'refresh' => false,
  50.     );
  51.     private $_inline_actions = array(
  52.     );
  53.     private $_events = array(
  54.         'onInsert' => null,
  55.         'onEdit' => null,
  56.         'onDelete' => null,
  57.         'afterInsert' => null,
  58.         'afterEdit' => null,
  59.         'afterDelete' => null,
  60.     );
  61.     private $_filters = array();
  62.     private $_columns = array();
  63.     private $_column_names = array();
  64.     private $_default_column_options = array(
  65.         'editable' => true,
  66.     );
  67.     private $_actions_options = array(
  68.         'edit' => array(
  69.             'reloadAfterSubmit' => true,
  70.             'closeAfterEdit' => true,
  71.             'closeOnEscape' => true,
  72.             'afterSubmit' => 'function(response) {return eval(response.responseText)}',
  73.             ),
  74.         'add' => array(
  75.             'reloadAfterSubmit' => true,
  76.             'closeAfterAdd' => true,
  77.             'closeOnEscape' => true,
  78.             'afterSubmit' => 'function(response) {return eval(response.responseText)}',
  79.             ),
  80.         'delete' => array(
  81.             'reloadAfterSubmit' => true,
  82.             'closeOnEscape' => true,
  83.             'afterSubmit' => 'function(response) {return eval(response.responseText)}',
  84.             ),
  85.         'search' => array(
  86.             'closeOnEscape' => true,
  87.             'multipleSearch' => true,
  88.             ),
  89.         'view' => array(
  90.             'closeOnEscape' => true,
  91.             ),
  92.     );
  93.     private $_methods = array(
  94.         //'filterToolbar' => array(
  95.         //  'stringResult' => true,
  96.         //  'searchOnEnter' => false,
  97.         //  ),
  98.         );
  99.     private $_table = null;
  100.     private $_table_pk = null;
  101.     private $_select = null;
  102.     private $_filter_method = 'where';
  103.  
  104.     public function __construct($table_name = null, $columns=array(), $options = array(), $actions = array(), $events = array())
  105.     {      
  106.         $this->_options['url'] = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
  107.         $this->_options['editurl'] = $this->_options['url'];
  108.  
  109.         $this->setTable($table_name);
  110.         $this->setColumns($columns);
  111.         $this->setOptions($options);
  112.         $this->setActions($actions);
  113.         $this->setEvents($events);
  114.     }
  115.    
  116.     public function setId($id)
  117.     {
  118.         $this->_id = $id;
  119.         $delim = (strpos($this->_options['url'], '?') === false)?'?':'&';
  120.         $this->_options['url'] = $this->_options['url'] . $delim . '_grid_id=' . $this->_id;
  121.         $this->_options['editurl'] = $this->_options['url'];
  122.     }
  123.    
  124.     public function setFilterMethodOr()
  125.     {
  126.         $this->_filter_method = 'orWhere';
  127.     }
  128.  
  129.     public function setTable($table_name)
  130.     {
  131.         $this->_table = $table_name;
  132.         $this->setTablePk("id");
  133.         $this->_select = "SELECT %s FROM $table_name";
  134.     }
  135.  
  136.     public function setTablePk($pk)
  137.     {
  138.         $this->_table_pk = $pk;
  139.         if($this->_table_pk)
  140.         {
  141.             $this->_options["jsonReader"]["id"] = $this->_table_pk;
  142.         }
  143.     }
  144.    
  145.     public function setKeyColumn($column)
  146.     {
  147.         $this->_options["jsonReader"]["id"] = $column;
  148.     }
  149.  
  150.     public function setColumns($columns)
  151.     {      
  152.         $this->_columns = array();
  153.         $this->_column_names = array();
  154.         $this->_options["colNames"] = array();
  155.         foreach($columns as $col)
  156.         {
  157.             $this->_options["colNames"][] = $col["title"];
  158.             if (!isset($col["virtual"]) || ($col["virtual"] != true))
  159.             {
  160.                 $this->_column_names[] = $col["name"];
  161.             }
  162.             $this->_columns[] = array_merge($this->_default_column_options, $col);
  163.         }
  164.     }
  165.  
  166.     public function setOptions($options)
  167.     {
  168.         if (empty($options))
  169.         {
  170.             $options = array();
  171.         }
  172.         $this->_options = array_merge($this->_options,$options);
  173.     }
  174.  
  175.     public function setDefaultColumnOptions($default_column_options)
  176.     {
  177.         if (empty($default_column_options))
  178.         {
  179.             $default_column_options = array();
  180.         }
  181.         $this->_default_column_options = array_merge($this->_default_column_options,$default_column_options);
  182.         $this->setColumns($this->_columns);
  183.     }
  184.  
  185.     public function setActions($actions)
  186.     {
  187.         if (empty($actions))
  188.         {
  189.             $actions = array();
  190.         }
  191.         $this->_actions = array_merge($this->_actions,$actions);
  192.     }
  193.  
  194.     public function setInlineActions($actions)
  195.     {
  196.         if (empty($actions))
  197.         {
  198.             $actions = array();
  199.         }
  200.         $this->_inline_actions = array_merge($this->_inline_actions,$actions);
  201.     }
  202.  
  203.     public function setEvents($events)
  204.     {
  205.         if (empty($events))
  206.         {
  207.             $events = array();
  208.         }
  209.         $this->_events = array_merge($this->_events,$events);
  210.     }
  211.  
  212.     public function setMethods($methods)
  213.     {
  214.         if (empty($methods))
  215.         {
  216.             $methods = array();
  217.         }
  218.         $this->_methods = array_merge($this->_methods,$methods);
  219.     }
  220.    
  221.     public function setFilters($filters)
  222.     {
  223.         $this->_filters = $filters;
  224.         $ns_name = \CsContext::getController()->getModule().".".\CsContext::getController()->getAction();
  225.         $ns = isset($_SESSION['jqFilters.'.$ns_name])?$_SESSION['jqFilters.'.$ns_name]:$_SESSION['jqFilters.'.$ns_name]=array();
  226.         if(!isset($ns['grid_filters'][$this->_id]))
  227.         {
  228.             $ns['grid_filters'][$this->_id] = array();
  229.         }
  230.         foreach ($this->_filters as &$filter)
  231.         {
  232.             $ns['grid_filters'][$this->_id][$filter['filterName']] = \CsContext::getRequest()->getParameter($filter['filterName'], isset($ns['grid_filters'][$this->_id][$filter['filterName']])?$ns['grid_filters'][$this->_id][$filter['filterName']]:null);
  233.         }
  234.         foreach ($this->_filters as &$filter)
  235.         {
  236.             if(isset($ns['grid_filters'][$this->_id][$filter['filterName']]))
  237.             {
  238.                 $filter['defaultValue'] = $ns['grid_filters'][$this->_id][$filter['filterName']];
  239.             }
  240.         }
  241.     }
  242.    
  243.     public function getFilterValue($pos)
  244.     {
  245.         return $this->_filters[$pos]['defaultValue'];
  246.     }
  247.    
  248.     private function executeOper($oper, $data)
  249.     {
  250.         switch($oper)    
  251.         {    
  252.             case "add":
  253.                 /*
  254.                 if($this->_events['onInsert'])
  255.                 {
  256.                     $continue = $this->_table->{$this->_events['onInsert']}($data);
  257.                 }
  258.                 if($continue === false)
  259.                 {
  260.                     break;
  261.                 }
  262.                 */
  263.                 unset($data['id']);
  264.                 $data['id'] = \CsContext::getDb()->insert($this->_table, $data);
  265.                 /*
  266.                 if($this->_events['afterInsert'])
  267.                 {
  268.                     $this->_table->{$this->_events['afterInsert']}($data);
  269.                 }
  270.                 */
  271.                 break;
  272.             case "edit":
  273.                 /*
  274.                 if($this->_events['onEdit'])
  275.                 {
  276.                     $continue = $this->_table->{$this->_events['onEdit']}($data);
  277.                 }
  278.                 if($continue === false)
  279.                 {
  280.                     break;
  281.                 }
  282.                 */
  283.                 $id = $data['id'];
  284.                 unset($data['id']);
  285.                 \CsContext::getDb()->update($this->_table, $data, "$this->_table_pk = $id");
  286.                 $data['id'] = $id;
  287.                 /*
  288.                 if($this->_events['afterEdit'])
  289.                 {
  290.                     $this->_table->{$this->_events['afterEdit']}($data);
  291.                 }
  292.                 */
  293.                 break;
  294.             case "del":
  295.                 /*
  296.                 if($this->_events['onDelete'])
  297.                 {
  298.                     $continue = $this->_table->{$this->_events['onDelete']}($data);
  299.                 }
  300.                 if($continue === false)
  301.                 {
  302.                     break;
  303.                 }
  304.                 */
  305.                 $id = $data['id'];
  306.                 \CsContext::getDb()->delete($this->_table, "$this->_table_pk IN ($id)");
  307.                 $data['id'] = $id;
  308.                 /*
  309.                 if($this->_events['afterDelete'])
  310.                 {
  311.                     $this->_table->{$this->_events['afterDelete']}($data);
  312.                 }
  313.                 */
  314.                 break;
  315.         }
  316.     }
  317.    
  318.     private function executeSearch()
  319.     {
  320.         if($searchField = $_REQUEST['searchField'])
  321.         {
  322.             $filters = array(
  323.                 'rules' => array(
  324.                     'field' => $searchField,
  325.                     'op' => $_REQUEST['searchOper'],
  326.                     'data' => $_REQUEST['searchString'],
  327.                 ),
  328.             );
  329.         }
  330.         else
  331.         {
  332.             $filters = json_decode(\CsContext::getRequest()->getGetParameter('filters'), true);            
  333.         }
  334.        
  335.         if($where = $this->constructSearchWhere($filters))
  336.         {
  337.             $this->_select .= " ".$this->_filter_method." ".$where;
  338.         }
  339.     }
  340.    
  341.     private function constructSearchWhere($filters)
  342.     {
  343.         return $this->_getWhereForGroup($filters);
  344.     }
  345.    
  346.     private function _getWhereForGroup($filters)
  347.     {
  348.         $s = "(";
  349.  
  350.         if(isset($filters['groups']) && $filters['groups'])
  351.         {
  352.             foreach ($filters['groups'] as $group)
  353.             {
  354.                 if($group_where = $this->_getWhereForGroup($group))
  355.                 {
  356.                     if (strlen($s) > 1)
  357.                     {
  358.                         if ($filters['groupOp'] === "OR")
  359.                         {
  360.                             $s .= " OR ";
  361.                         }
  362.                         else
  363.                         {
  364.                             $s .= " AND ";
  365.                         }
  366.                     }
  367.                     $s .= $group_where;
  368.                 }
  369.             }
  370.         }
  371.  
  372.         if (isset($filters['rules']) && $filters['rules']) {
  373.             foreach ($filters['rules'] as $rule)
  374.             {
  375.                 if(($rule['data'] !==null) && ($rule['data'] !==''))
  376.                 {
  377.                     if (strlen($s) > 1)
  378.                     {
  379.                         if ($filters['groupOp'] === "OR")
  380.                         {
  381.                             $s .= " OR ";
  382.                         }
  383.                         else  {
  384.                             $s .= " AND ";
  385.                         }
  386.                     }
  387.                     $s .= $this->_getWhereForRule($rule);
  388.                 }
  389.             }
  390.         }
  391.  
  392.         $s .= ")";
  393.  
  394.         if ($s == "()") {
  395.             return ""; // ignore groups that don't have rules
  396.         } else {
  397.             return $s;
  398.         }
  399.     }
  400.    
  401.     private function _getWhereForRule($rule)
  402.     {
  403.             if($rule['op'] == 'in' || $rule['op'] == 'ni')
  404.             {
  405.                 $question = " (?)";
  406.                 return $rule['field'].$this->_where_rules[$rule['op']].' ('.implode(',', array_map(function($val){return "'$val'";}, is_array($rule['data'])?$rule['data']:explode(',', $rule['data']))).')';
  407.             }
  408.             if($rule['op'] == 'nu' || $rule['op'] == 'un')
  409.             {
  410.                 $question = " (?)";
  411.                 return $rule['field'].$this->_where_rules[$rule['op']];
  412.             }
  413.            
  414.             if($rule['op']=='bw' || $rule['op']=='bn')
  415.             {
  416.                 $rule['data'] =  $rule['data'] . "%";
  417.             }  
  418.             elseif ($rule['op']=='ew' || $rule['op']=='en')
  419.             {
  420.                 $rule['data'] =  "%" . $rule['data'];
  421.             }  
  422.             elseif ($rule['op']=='cn' || $rule['op']=='nc')
  423.             {
  424.                 $rule['data'] =  "%" . $rule['data'] . "%";
  425.             }
  426.        
  427.             return $rule['field'].$this->_where_rules[$rule['op']]." '". $rule['data']."'";
  428.     }
  429.  
  430.     public function render($grid_id = "grid")
  431.     {
  432.         if(!$this->_select)
  433.         {
  434.             throw new \Exception('You should define data source for the grid!');
  435.         }
  436.        
  437.         if(\CsContext::getRequest()->getParameter('_grid_id') == $this->_id)
  438.         {
  439.             if(\CsContext::getRequest()->getPostParameter('oper'))
  440.             {
  441.                 $result = array(true);
  442.                
  443.                 $post_params = $_POST;
  444.                 unset($post_params['oper']);           
  445.                
  446.                 try
  447.                 {
  448.                     $this->executeOper($_POST['oper'], $post_params);
  449.                 }
  450.                 catch (\Exception $e)
  451.                 {
  452.                     $result = array(false, $e->getMessage());
  453.                 }
  454.                
  455.                 echo json_encode($result);exit;
  456.             }
  457.            
  458.             if(\CsContext::getRequest()->getGetParameter('_search')=='true')
  459.             {
  460.                 $this->executeSearch();
  461.             }
  462.            
  463.             //echo($this->_select);exit;
  464.            
  465.             $this->_select = sprintf($this->_select, implode(", ", $this->_column_names));
  466.            
  467.             if(\CsContext::getRequest()->getGetParameter('oper')=='excel')
  468.             {
  469.                 return $this->_select;
  470.             }
  471.             //echo $this->_select;exit;
  472.             if (\CsContext::getRequest()->getGetParameter('page'))
  473.             {
  474.                 $page = \CsContext::getRequest()->getGetParameter('page');
  475.                 if(!$page) $page = 1;
  476.                 $page_rows = \CsContext::getRequest()->getGetParameter('rows');
  477.                 if(!$page_rows) $page_rows = 20;
  478.                 $sidx = \CsContext::getRequest()->getGetParameter('sidx');
  479.                 $sord = \CsContext::getRequest()->getGetParameter('sord');
  480.                                    
  481.                 if($sidx)
  482.                 {
  483.                     $this->_select .= " ORDER BY $sidx $sord";
  484.                 }
  485.                 $data = array();
  486.                 $data['records'] = \CsContext::getDb()->query("SELECT COUNT(*) FROM (".$this->_select.") t")->fetchColumn();
  487.                
  488.                 $limit_start = ($page - 1) * $page_rows;
  489.                 $this->_select .= " LIMIT $limit_start, $page_rows";
  490.                
  491.                
  492.                 $data['page'] = $page;
  493.                 $data['total'] = ceil($data['records']/$page_rows);
  494.                
  495.                 //echo $this->_select; exit;
  496.                 $data['rows'] = \CsContext::getDb()->query($this->_select)->fetchAll();
  497.                 //var_dump($data); exit;
  498.                
  499.                 echo json_encode($data);exit;
  500.             }
  501.         }
  502.  
  503.         if(!empty($this->_inline_actions))
  504.         {
  505.             //echo 111; exit;
  506.             array_push($this->_options["colNames"], 'Действия');
  507.             array_push($this->_columns, array("name"=>"act", "align"=>"center", "index"=>"act", "width"=>"30", "sortable"=>false, "search"=>false));
  508.  
  509.                 $err_func = 'function(response) {var data = eval(response.responseText); if(!data[0]) $.jgrid.info_dialog($.jgrid.errors.errcap,data[1], $.jgrid.edit.bClose); else {jQuery(event.target).parent().parent().children().toggle();} return data[0];}';
  510.                 $this->_options['gridComplete'] .= "function(){
  511. var ids = jQuery('#$grid_id').jqGrid('getDataIDs');
  512.     for(var i=0;i < ids.length;i++){
  513.         var cl = ids[i];
  514.         be = ' <a title=\"Edit this row\" class=\"ui-icon ui-icon-pencil\" style=\"display: inline-block; padding: 0; margin-right: .1em; text-align: center;\" href=\"javascript:void(0);\" onclick=\"jQuery(\'#$grid_id\').jqGrid(\'editRow\', '+cl+', true, null, $err_func); jQuery(event.target).parent().parent().children().toggle();\">Edit</a>';
  515.         de = ' | <a title=\"Delete this row\" class=\"ui-icon ui-icon-trash\" style=\"display: inline-block; padding: 0; margin-right: .1em; text-align: center;\" href=\"javascript:void(0);\" onclick=\"jQuery(\'#$grid_id\').delGridRow('+cl+');\">Delete</a>';
  516.         se = ' <a title=\"Save this row\" class=\"ui-icon ui-icon-disk\" style=\"display: inline-block; padding: 0; margin-right: .1em; text-align: center;\" href=\"javascript:void(0);\" onclick=\"jQuery(\'#$grid_id\').saveRow('+cl+',$err_func);\">Save</a>';
  517.         ce = ' | <a title=\"Restore this row\" class=\"ui-icon ui-icon-cancel\" style=\"display: inline-block; padding: 0; margin-right: .1em; text-align: center;\" href=\"javascript:void(0);\" onclick=\"jQuery(\'#$grid_id\').restoreRow('+cl+'); jQuery(this).parent().hide(); jQuery(this).parent().prev().show();\">Cancel</a>';
  518.         jQuery('#$grid_id').jqGrid('setRowData',ids[i],{act:'<span id=\"edit_row_'+cl+'\">'+be+de+'</span>'+'<span style=display:none id=\"save_row_'+cl+'\">'+se+ce+'</span>'});
  519.     }
  520. }";
  521.                 $this->_options['ondblClickRow'] = "function(id){
  522.     if(id && id!==lastSel) {
  523.         jQuery('#$grid_id').restoreRow(lastSel);
  524.         jQuery('#edit_row_'+lastSel).parent().children().toggle();
  525.         lastSel=id;
  526.     }
  527.     jQuery('#$grid_id').jqGrid('editRow', id, true, null, function(response) {var data = eval(response.responseText); if(!data[0]) $.jgrid.info_dialog($.jgrid.errors.errcap,data[1], $.jgrid.edit.bClose); else {jQuery('#edit_row_'+id).parent().children().toggle();} return data[0];});
  528.     jQuery('#edit_row_'+id).parent().children().toggle();
  529. }";
  530.         }
  531.        
  532.         $this->_options['pager'] = '#'.$grid_id.'_pager';
  533.         $this->_options['colModel'] = $this->_columns;
  534.  
  535.         $encoded_options = $this->_encodeJson($this->_options);
  536.        
  537.  
  538.         ob_start();
  539.        
  540.         ?>
  541. <table id="<?php echo $grid_id?>"></table>
  542. <div id="<?php echo $grid_id."_pager"?>"></div>
  543. <div id="<?php echo $grid_id."_search"?>"></div>
  544.  
  545. <script>    
  546. jQuery.jgrid.extend({
  547.     navFilterAdd:function (elem,p) {
  548.         p = $.extend({
  549.             filterDefaultId: 'myfilter',
  550.             filters: [],
  551.             filterGroupOp: 'AND',
  552.             sField:'searchField',
  553.             sValue:'searchString',
  554.             sOper: 'searchOper',
  555.             sFilter: 'filters'
  556.         }, p ||{});
  557.         return this.each(function() {
  558.             var $t = this;
  559.             if( !$t.grid)  { return; }
  560.             if( elem.indexOf("#") !== 0) { elem = "#"+elem; }
  561.             var findnav = $(".navtable",elem)[0];
  562.             if(findnav) {
  563.  
  564.                 var setSdata = function(reset)
  565.                 {
  566.                     var filters = {}, groups = [], sdata={}, res;
  567.  
  568.                     filters.groupOp = p.filterGroupOp;
  569.                    
  570.                     $.each(p.filters, function(i, pFilter){
  571.                         var fid = $t.id + "_" + p.filterDefaultId + "_" + pFilter.filterName;
  572.                         var fdata;
  573.                         if(reset == true) {
  574.                             if(pFilter.filterType == 'checkbox') {
  575.                                 $('#'+fid).attr('checked', false);
  576.                             }
  577.                             else {
  578.                                     $('#'+fid).val('');
  579.                             }
  580.                         }
  581.  
  582.                         if(pFilter.filterType == 'checkbox')
  583.                         {
  584.                             if($('#'+fid).attr('checked'))
  585.                             {
  586.                                 fdata = $('#'+fid).val();
  587.                             }
  588.                             else
  589.                             {
  590.                                 fdata = '';
  591.                             }
  592.                         }
  593.                         else
  594.                         {
  595.                             fdata = $('#'+fid).val();
  596.                         }
  597.                            
  598.                         sdata[pFilter.filterName] = fdata;
  599.                        
  600.                         var fRules = pFilter.filterRules;
  601.  
  602.                         function setData(fRules, fdata)
  603.                         {
  604.                             if(fRules.groups) {
  605.                                 fRules.groups = setData(fRules.groups, fdata);
  606.                             }
  607.                             $.each(fRules.rules, function(i, n){
  608.                                 n.data = fdata;
  609.                                 });
  610.                             return fRules;
  611.                         }
  612.  
  613.                         fRules = setData(fRules, fdata);
  614.                         groups.push(fRules);
  615.                     });
  616.                    
  617.                     filters.groups = groups;
  618.                                        
  619.                     try {
  620.                         // xmlJsonClass or JSON.stringify
  621.                         res = xmlJsonClass.toJson(filters, '', '', false);
  622.                     } catch (e) {
  623.                         try {
  624.                             res = JSON.stringify(filters);
  625.                         } catch (e2) { }
  626.                     }
  627.                     if(typeof(res)==="string") {
  628.                         sdata[p.sFilter] = res;
  629.                         $.each([p.sField,p.sValue, p.sOper], function() { sdata[this] = "";});
  630.                     }
  631.                    
  632.                     $t.p.search = true;
  633.                     $.extend($t.p.postData,sdata);
  634.                 }
  635.                
  636.                 var sendFilterData = function()
  637.                 {
  638.                     setSdata();
  639.                    
  640.                     $($t).trigger("reloadGrid",[{page:1}]);
  641.                    
  642.                     return false;
  643.                 }
  644.  
  645.                 function clearFilterData() {
  646.                     setSdata(true);
  647.                    
  648.                     $($t).trigger("reloadGrid",[{page:1}]);
  649.                    
  650.                     return false;
  651.                 }
  652.                
  653.                 $.each(p.filters, function(i, pFilter){
  654.  
  655.                     var tbd = $("<td></td>");
  656.                     $(tbd).addClass('ui-search-toolbar ui-th-ltr').css('padding', '0px 2px').append(pFilter.filterText);
  657.  
  658.                     var fid = $t.id + "_" + p.filterDefaultId + "_" + pFilter.filterName;
  659.  
  660.                     if(pFilter.filterType == 'text') {
  661.                         var filter = $("<input type='text' id='" + fid + "' />");
  662.                         if(pFilter.defaultValue)
  663.                         {
  664.                             filter.val(pFilter.defaultValue);
  665.                         }
  666.                        
  667.                         filter.keypress(function(e){
  668.                             if(e.keyCode ==13 ) {
  669.                                 return sendFilterData();
  670.                             }
  671.                         });
  672.                     }
  673.                     if(pFilter.filterType == 'datepicker') {
  674.                         var filter = $("<input type='text' id='" + fid + "' />");
  675.                         if(pFilter.defaultValue)
  676.                         {
  677.                             filter.val(pFilter.defaultValue);
  678.                         }
  679.  
  680.                         $(document).ready(function(){$(filter).datepicker({ dateFormat: 'yy-mm-dd' });});
  681.                        
  682.                         filter.change(function(e){
  683.                             return sendFilterData()
  684.                         });
  685.                        
  686.                         filter.keypress(function(e){
  687.                             if(e.keyCode ==13 ) {
  688.                                 return sendFilterData();
  689.                             }
  690.                         });
  691.                     }
  692.                     else if(pFilter.filterType == 'select') {
  693.                         if(pFilter.filterNochoice) {
  694.                             var nochoice = pFilter.filterNochoice;
  695.                         }
  696.                         else {
  697.                             var nochoice = '';
  698.                         }
  699.                            
  700.                         var filter = $("<select id='" + fid + "'></select>").append('<option value="">'+nochoice+'</option>');
  701.                        
  702.                         $.each(pFilter.filterOptions, function(i,n){filter.append('<option value="'+i+'">'+n+'</option>')});
  703.  
  704.                         if(pFilter.defaultValue)
  705.                         {
  706.                             $("option[value='" + pFilter.defaultValue + "']", filter).attr('selected', true);
  707.                         }                      
  708.                        
  709.                         filter.change(function(e){
  710.                             return sendFilterData()
  711.                         });
  712.                     }
  713.                     else if(pFilter.filterType == 'multiselect') {
  714.                         if(pFilter.filterNochoice) {
  715.                             var nochoice = pFilter.filterNochoice;
  716.                         }
  717.                         else {
  718.                             var nochoice = '';
  719.                         }
  720.                        
  721.                         var filter = $("<select id='" + fid + "' name='" + fid + "' multiple='multiple'></select>");
  722.                        
  723.                         $.each(pFilter.filterOptions, function(i,n){filter.append('<option value="'+i+'">'+n+'</option>')});
  724.  
  725.                         if(pFilter.defaultValue)
  726.                         {
  727.                             $.each(pFilter.defaultValue, function(i,n){$("option[value='" + n + "']", filter).attr('selected', true)});
  728.                         }
  729.  
  730.                         $(document).ready(function(){$(filter).multiselect({
  731.                                 position:{
  732.                                       my: 'top',
  733.                                       at: 'top'
  734.                                     },
  735.                                 minWidth: '210',
  736.                                 selectedList: '3',
  737.                                 header: pFilter.filterText,
  738.                                 noneSelectedText: 'Клик для выбора',
  739.                                 selectedText: 'Выбрано: #'  
  740.                             }).multiselectfilter({
  741.                                 label: '',
  742.                                 width: 60,
  743.                                 placeholder: 'Поиск'          
  744.                             });
  745.                         });
  746.                        
  747.                         filter.change(function(e){
  748.                             return sendFilterData()
  749.                         });
  750.                     }
  751.                     else if(pFilter.filterType == 'checkbox') {
  752.                         var filter = $("<input type='checkbox' id='" + fid + "' value='" + pFilter.filterOptions + "' />");
  753.                        
  754.                         if(pFilter.defaultValue !== "")
  755.                         {
  756.                             filter.attr('checked', true);
  757.                         }
  758.                        
  759.                         filter.change(function(e){
  760.                             return sendFilterData()
  761.                         });
  762.                     }
  763.                    
  764.    
  765.                     $(tbd).append($(filter));
  766.                     $("tr",findnav).append(tbd);
  767.                 });
  768.  
  769.                 $("tr",findnav).append(
  770.                     $("<td id='clear_filter' title='Очистить все фильтры'></td>")
  771.                     .addClass('ui-pg-button ui-corner-all')
  772.                     .css('padding-left', '2px')
  773.                     .append(
  774.                         $("<div></div>")
  775.                         .addClass('ui-pg-div')
  776.                         .append(
  777.                             $("<span></span>")
  778.                             .addClass('ui-icon ui-icon-close')
  779.                             )
  780.                         )
  781.                     .click(
  782.                         function(){return clearFilterData()}
  783.                         )
  784.                     );
  785.             }
  786.             setSdata();
  787.         });
  788.     }
  789. });
  790.  
  791.     jQuery(document).ready(function(){
  792.     <?php echo $this->render_js($grid_id,$encoded_options);?>
  793.     });            
  794. </script>
  795.         <?php
  796.            
  797.         return ob_get_clean();
  798.     }
  799.    
  800.     public function render_js($grid_id,$encoded_options)
  801.     {
  802.         $encoded_actions = $this->_encodeJson($this->_actions);
  803.         $encoded_edit_options = $this->_encodeJson($this->_actions_options['edit']);
  804.         $encoded_add_options = $this->_encodeJson($this->_actions_options['add']);
  805.         $encoded_delete_options = $this->_encodeJson($this->_actions_options['delete']);
  806.         $encoded_search_options = $this->_encodeJson($this->_actions_options['search']);
  807.         $encoded_view_options = $this->_encodeJson($this->_actions_options['view']);
  808.     ?>
  809. var lastSel;
  810. var grid_<?php echo $grid_id?> = jQuery("#<?php echo $grid_id?>").jqGrid(<?php echo $encoded_options?>);
  811. jQuery("#<?php echo $grid_id?>").jqGrid('navGrid','#<?php echo $grid_id."_pager"?>',
  812.     <?php echo $encoded_actions?>,
  813.     <?php echo $encoded_edit_options?>,
  814.     <?php echo $encoded_add_options?>,
  815.     <?php echo $encoded_delete_options?>,
  816.     <?php echo $encoded_search_options?>,
  817.     <?php echo $encoded_view_options?>
  818. );
  819. <?php foreach ($this->_methods as $method=>$method_options):?>
  820.     jQuery("#<?php echo $grid_id?>").jqGrid('<?php echo $method; ?>',"#<?php echo $grid_id."_pager"?>", <?php echo $this->_encodeJson($method_options); ?>);   
  821. <?php endforeach;?>
  822. <?php if(!empty($this->_filters)): ?>
  823. jQuery("#<?php echo $grid_id?>").jqGrid('navFilterAdd', "#<?php echo isset($this->_options['filterContainer'])?$this->_options['filterContainer']:$grid_id."_pager"?>", {filters: <?php echo $this->_encodeJson($this->_filters); ?>});
  824. <?php endif; ?>
  825. <?php if($this->_options['height'] === null): ?>
  826. jQuery("#<?php echo $grid_id?>").setGridHeight(jQuery(document).height()-350);
  827. <?php endif; ?>
  828. grid_<?php echo $grid_id?>.setGridParam({datatype: 'json'});
  829. grid_<?php echo $grid_id?>.trigger('reloadGrid');
  830.  
  831.     <?php
  832.     }
  833.    
  834.    
  835.     /**
  836.      * Кодирует в json. Если на нулевом уровне вложенности в значениях встречаеться функция - НЕ делает из нее строку.
  837.      */
  838.    
  839.     private function _encodeJson($data)
  840.     {
  841.         $value_arr = array();
  842.         $replace_keys = array();
  843.         $this->_replaceFunctionsForJson($data, $replace_keys, $value_arr);
  844.         $json = json_encode($data);
  845.         $json = str_replace($replace_keys, $value_arr, $json);
  846.         return $json;
  847.     }
  848.    
  849.     private function _replaceFunctionsForJson(&$data, &$replace_keys, &$value_arr, &$i = 0)
  850.     {
  851.         foreach($data as $key => &$value)
  852.         {
  853.             if(is_array($value))
  854.             {
  855.                 $this->_replaceFunctionsForJson($value, $replace_keys, $value_arr, $i);
  856.             }
  857.             elseif(strpos($value, 'function(')===0)
  858.             {
  859.                 $i++;
  860.                 $value_arr[] = $value;
  861.                 $value = '%%' . $i . '%%';
  862.                 $replace_keys[] = '"' . $value . '"';
  863.             }
  864.         }
  865.     }
  866. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement