Advertisement
Guest User

Untitled

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