synergy/synergydatagrid

使用 jqGrid JavaScript 插件在网格中显示数据的模块

安装次数: 2,008

依赖者: 2

建议者: 0

安全: 0

星标: 20

关注者: 7

分支: 20

开放问题: 7

语言:JavaScript

类型:synergy-module


README

Build Status Latest Stable Version Total Downloads composer.lock Build Status Coverage Status

SynergyDataGrid (ZF3 模块)

简介

SynergyDataGrid 是一个 Zend Framework 3 模块,它简化了在 ZF3 应用程序中使用 JqGrid

它提供了基于 AJAX 的网格的基本 CRUD 功能,用于编辑数据库表。有关所有可用的 jqGrid 插件和库功能,请参阅 http://www.trirand.com/jqgridwiki/doku.php 上的 jqGrid 文档。

##依赖

可选

未来开发计划包括

  • Doctrine ODM 网格
  • Zend DB 网格

安装

手动安装

  1. 转到您的项目目录。
  2. 将此项目作为 synergydatagrid 模块克隆到您的 ./vendor/synergy/ 目录

git clone https://github.com/odiaseo/zf2-datagrid.git

  1. 将公共目录中的所有文件复制到您的项目公共文件夹

使用 Composer

  1. 转到您的项目目录。
  2. 运行命令 composer require "synergy/synergydatagrid"
  3. 按照以下安装后步骤操作

对于 ZF2 项目,请使用版本 < 2.0

安装后步骤

目前,此模块仅支持 Doctrine ORM 实体,因此请确保 DoctrineORM 配置正确。

用法

  • 在您的控制器类中
         public function gridAction() {
               //replace {Entity_Name} with your entity name e.g. 'Application\Entity\User'

               $serviceManager = $this->getServiceLocator() ;
               $grid = $serviceManager->get('jqgrid')->setGridIdentity({Entity_Name});

               $grid->setUrl('your_custom_crun_url'); //optional, if not set the default CRUD controller would be used

               return array('grid' => $grid);
         }
  • 在您的视图脚本中
        echo $this->displayGrid($this->grid);
  • 默认情况下,JavaScript 代码将使用 headScript 视图助手附加到页面的 head 部分并在文档加载时执行
  • 如果您不希望在加载时执行脚本,请将 render_script_as_template 选项设置为 true。代码将包裹在一个 script 标签中,类型为 text/x-jquery-tmpl
  • 如果您想访问 html 和 JavaScript,将第二个参数传递为 false,即 $params = $this->displayGrid($this->grid, false);。将返回一个包含 htmljsonLoad 脚本的关联数组。如果您正在制作 AJAX 请求以生成网格,这很有用。
  • 在布局的 head 部分中
             $this->headLink()->appendStylesheet('/jqGrid/css/ui.jqgrid.css')
                     ->appendStylesheet('/css/jquery.ui.datepicker.css')
                     ->appendStylesheet('/plugins/ui.multiselect.css') ;



             $this->headScript()->prependFile('https://ajax.googleapis.ac.cn/ajax/libs/jqueryui/1.8/jquery-ui.min.js', 'text/javascript')
                    ->prependFile('https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.8/jquery.min.js', 'text/javascript')
                    ->appendFile('/jqGrid/js/i18n/grid.locale-en.js', 'text/javascript')
                    ->appendFile('/plugins/ui.multiselect.js', 'text/javascript')
                    ->appendFile('/jqGrid/js/jquery.jqGrid.min.js', 'text/javascript') ;

设置网格选项

您可以使用/设置任何 jqgrid 选项(请参阅 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options),例如,要将 "datatype" 设置为 local,在控制器中添加以下代码

          $grid->setDatatype('local');

逻辑是将 "set" 附加到任何选项,并将其添加到网格中。

添加 ColModel 选项

可以将所有列模型选项添加到网格中(请参阅 http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options)。在网格配置文件或 module.config.php 中,指定模型选项,例如。

    return array(
        .......
        'jqgrid' => array (
            'column_model'  => array(
                'my_column'       => array(
                    'align'       => 'center',
                    'formatter'   => new Laminas\Json\Expr('your code goes here'),
                    'unformat'    => new Laminas\Json\Expr('your code goes here'),
                    'edittype'    => 'custom',
                    'editoptions' => array(
                        'custom_element' => new Laminas\Json\Expr('your code goes here'),
                        'custom_value'   => new Laminas\Json\Expr('your code goes here')
                    )
                ),
        )
    );

添加自定义 JavaScript

如果您想添加要与网格脚本一起渲染的附加 JavaScript,可以这样做

             $grid->getJsCode()->addCustomScript( new \Laminas\Json\Expr(" and your script here" ));

             $grid->getJsCode()->addCustomScript("add your script here");

添加子网格

您可以以以下方式添加子网格

  1. 从实体文件中,注意你想显示为子网格的类属性。它应该是一个关联字段,例如ManyToOne等。修改你的网格配置文件或添加到你的module.config.php中
  • 我们希望将字段my_field显示为子网格
             return array(
                 .......
                 'jqgrid' => array (
                        'column_model'  => array(
                            'my_field'       => array(
                                'isSubGrid' => true
                             ),
                        )
                  );
  • 我们希望将my_field显示为subgrid_as_grid
                  return array(
                                 .......
                         'jqgrid' => array (
                                  'column_model'  => array(
                                       'my_field'       => array(
                                           'isSubGridAsGrid' => true
                                       ),
                                 )
                         );
  1. 在返回网格数据的控制器操作中,你需要将一个数组作为prepareGridData函数的第二个参数传递。数组应该有一个'fieldName'键,该键指向从其获取数据的实体字段。fieldName是主实体类上joinColumn的名称。
           public function crudAction(){              ......
               $className = 'your_class_name';
               $options['fieldName'] = $this->params()->fromRoute('fieldName', null);
               $serviceManager = $this->getServiceLocator();
               $grid = $serviceManager->get('jqgrid');
               $grid->setGridIdentity($className);
               $response = $grid->prepareGridData($this->getRequest(), $options);
             .....
           }
  1. 你需要指定一个回调函数来返回要显示给网格的子网格editUrl。默认为空。传递给回调函数的参数是
  • $sm = 服务定位器;
  • $entity = 当前实体(FQCN)
  • $fieldName = 关联列的字段名
  • $targetEntity = 目标实体的FQCN
  • $urlTypes :
    • const DYNAMIC_URL_TYPE_GRID = 1; //这是获取主数据的数据url
    • const DYNAMIC_URL_TYPE_EDIT = 2; // 主网格的editurl
    • const DYNAMIC_URL_TYPE_SUBGRID = 3; // CRUD的子网格的edit url
    • const DYNAMIC_URL_TYPE_ROW_EXPAND = 4; // 子网格AsGrid的row expand url,用于加载数据
  1. 您的路由应该处理fieldName参数,该参数将在您的CRUD操作中获取。请注意,“subgridid”作为查询参数附加到url上。“row_id”是JavaScript变量,当返回子网格editUrl时将被替换,所以只需按示例所示附加即可。
         'jqgrid' => array(
              ........
              'grid_url_generator'  => function ($sm, $entity, $fieldName, $targetEntity, $urlType) {
                   switch($urlType){
                        .....
                         case  BaseGrid::DYNAMIC_URL_TYPE_ROW_EXPAND:
                          //@var $helper \Laminas\View\Helper\Url
                           $helper = $sm->get('viewhelpermanager')->get('url');
                           $url    = $helper('your_route_name',
                                     array(
                                             'your_parameters',
                                             'fieldName' => $fieldName
                                     )
                             );
                          return new \Laminas\Json\Expr("'$url?subgridid='+row_id");
                      }
                )

网格特定选项(多个网格)

如果您有多个网格,它们有不同的配置要求,可以为每个网格设置网格特定选项。

  1. 通过在控制器操作中指定setGridIdentity()方法的第二个参数来为网格添加一个唯一的ID。例如:
          ........
          $gridId = 'my_unique_id ;
          $grid = $serviceManager->get('jqgrid')->setGridIdentity( $className, $gridId);
          ......
  1. 在您的module.config.php文件中,按如下方式添加网格特定选项
         return array(
              .......
              'jqgrid' => array (
                     ......
                     'my_unique_id' => array(
                                      .............
                      )
               )
         );

网格特定选项将合并到具有该ID的网格的主网格选项中。

树形网格

要渲染树形网格,在控制器操作中将setGridIdentity()方法的第三个参数设置为true。这取决于Gedmo扩展的doctrine。实体类应该实现为此功能所需的Gedmo树注解;

自定义查询

默认情况下,网格从指定的实体加载数据到网格中,不使用任何WHERE子句。如果您想指定一个WHERE子句,当填充网格时使用,可以通过创建自定义QueryBuilder构建器并将其设置在网格中来实现,如下所示

在您的控制器中

       
           ......
           $grid  = $serviceManager->get('jqgrid');

           $qb    = $grid->getEntityManager()->createQueryBuilder();
           $alias = $grid->getModel()->getAlias();

           $qb->where($alias . '.your_field', ':param')
                   ->setParameter(':param', 'your_value');

           $grid->setCustomQueryBuilder($qb);
           ........

其他过滤参数将按常规添加到QueryBuilder中。唯一不同的是,不是创建新的QueryBuilder,模块使用自定义QueryBuilder。您还需要将过滤参数添加到url中,以便在网格上应用分页和过滤器。您可以通过在设置网格标识时向网格添加自定义过滤器来完成此操作,如下所示

            
            $queryParam  = [
                'customFilters' => json_encode(
                    [
                        'groupOp' => 'AND',
                        'rules'   => [
                            [
                                'field' => 'isActive',
                                'op'    => 'eq',
                                'data'  => 1
                            ],
                            [
                                'field' => 'offerCount',
                                'op'    => 'gt',
                                'data'  => 0
                            ],
                            [
                                'field' => 'logo',
                                'op'    => 'eq',
                                'data'  => ''
                            ],
                        ]
                   ]
            )
        ];
     
        $grid = $this->getServiceLocator()->get('jqgrid');
        $grid->setGridIdentity($className, $entityKey, null, false, $queryParam);
     
#Configuration Options


```php

        'jqgrid'       => array(
                /**
                 * Allow retrieval of data from a different domain
                 * All CRUD request would be prefixed with the api_domain value
                 * e.g. http://www.example.com
                 */
                'api_domain'                        => '',
                /**
                 * Location where entity classname to entity key mappings are stored
                 */
                'entity_cache'                      => array(
                    'orm' => 'data/SynergyDataGrid/cache/orm_entity_classmap.php',
                    'odm' => 'data/SynergyDataGrid/cache/odm_entity_classmap.php',
                ),

                /**
                 * settings for customising plugins e.g. jquery datepicker
                 */
                'plugins'                           => array(
                    'date_picker' => array(
                        'dateFormat' => 'D, d M yy',
                        'timeFormat' => 'hh:mm'
                    )
                ),
                /**
                 * The default value of this property is:
                 * {page:“page”,rows:“rows”, sort:“sidx”, order:“sord”, search:“_search”, nd:“nd”, id:“id”, oper:“oper”, editoper:“edit”, addoper:“add”, deloper:“del”, subgridid:“id”,
                 * npage:null, totalrows:“totalrows”}
                 * This customizes names of the fields sent to the server on a POST request. For example, with this setting,
                 * you can change the sort order element from sidx to mysort by setting prmNames: {sort: “mysort”}. The string that will be POST-ed to the server will then be
                 * myurl.php?page=1&rows=10&mysort=myindex&sord=asc rather than myurl.php?page=1&rows=10&sidx=myindex&sord=asc
                 * So the value of the column on which to sort upon can be obtained by looking at $POST['mysort'] in PHP.
                 * When some parameter is set to null, it will be not sent to the server. For example if we set
                 * prmNames: {nd:null} the nd parameter will not be sent to the server. For npage option see the scroll option.
                 * These options have the following meaning and default values:
                 *
                 * page: the requested page (default value page)
                 * rows: the number of rows requested (default value rows)
                 * sort: the sorting column (default value sidx)
                 * order: the sort order (default value sord)
                 * search: the search indicator (default value _search)
                 * nd: the time passed to the request (for IE browsers not to cache the request) (default value nd)
                 * id: the name of the id when POST-ing data in editing modules (default value id)
                 * oper: the operation parameter (default value oper)
                 * editoper: the name of operation when the data is POST-ed in edit mode (default value edit)
                 * addoper: the name of operation when the data is posted in add mode (default value add)
                 * deloper: the name of operation when the data is posted in delete mode (default value del)
                 * totalrows: the number of the total rows to be obtained from server - see rowTotal (default value totalrows)
                 * subgridid: the name passed when we click to load data in the subgrid (default value id)
                 *
                 *  override the default by adding your params to this options in your config
                 */
                'prmNames'                          => array(),

                /**
                 * If set to true, the grid will be loaded with data from the database onload.
                 * If false, the grid will be loaded with data after page load via ajax
                 */
                'first_data_as_local'               => true,

                /**
                 * The JavaScript code to generate the grid is added to the headScript.
                 * If set to true, the type attribute of the script table would be set to text/x-jquery-tmpl
                 * instead of text/javascript e.g. headScript()->appendScript($onLoadScript, 'text/x-jquery-tmpl', array("id='ID'", 'noescape' => true))
                 *
                 * useful if you use plugins like require.js. You can then eval() the script in the callback function e.g.
                 * define([jquery], function($){ var gridScript = $('script[type="text/x-jquery-tmpl"]').text();
                 * $.globalEval(gridScript);
                 * }}
                 */
                'render_script_as_template'         => false,

                /**
                 * If set to true, whitespaces would be remove from the generated javascript code
                 * experimental!
                 */

                'compress_script'                   => false,
                /**
                 * If true, it adds a additional column to every row with edit/delete buttons
                 */
                'add_action_column'                 => true,


                /**
                 * When the action column id added to the grid, by default the normal form buttons are not
                 * displayed on the nav toolbar. If set to true, the buttons will be displayed in addition
                 * to the
                 */
                'allow_form_edit'                   => true,

                /**
                 * loads the entire tree on first load. Set to false to load on the top level
                 * deeper levels would be load on click via ajax
                 *
                 */
                'tree_load_all'                     => true,

                /**
                 * These are options specific to tree grids
                 * The gedmo/doctrine-extensions module is required for this to work
                 *
                 * @see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:treegrid&s[]=treegrid
                 */
                'tree_grid_options'                 => array(
                    'gridview'          => false,
                    'treeGridModel'     => 'nested',
                    'ExpandColumn'      => 'title',
                    'ExpandColumnWidth' => 120,
                    'treeReader'        => array(
                        'level_field'    => 'level',
                        'left_field'     => 'lft',
                        'right_field'    => 'rgt',
                        'leaf_field'     => 'isLeaf',
                        'expanded_field' => 'expanded',
                    )
                ),

                /**
                 * Grid options
                 * All valid jqgrid options can be added here
                 * When adding function use \Zend\Expr\Expr e.g. new \Laminas\Json\Expr('function(){ alert("i am here");}')
                 *
                 * @see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
                 */
                'grid_options'                      => array(
                    'datatype'           => 'json',
                    'mtype'              => 'POST',
                    'viewrecords'        => true,
                    'height'             => 'auto',
                    'allowResizeColumns' => true,
                    'sortable'           => true,
                    'viewsortcols'       => array(true, 'vertical', true),
                    'rowList'            => array(5, 10, 25, 50, 100),
                    'rowNum'             => 25,
                    'rows'               => true,
                    'autowidth'          => false,
                    'forceFit'           => true,
                    'gridview'           => true,
                    'multiselect'        => true,
                    'multiboxonly'       => false,
                    'rownumbers'         => false,
                    //add buttons to display on each row (action column)
                    'rowActionButtons'   => array()

                ),
                /**
                 * When rendering the grid, columns with these attributes would not be displayed at all
                 *
                 */
                'excluded_columns'                  => array(),

                /**
                 * These columns would not be editable
                 *
                 * @deprecated see column_model option
                 */
                'non_editable_columns'              => array(),

                /**
                 * These columns would be hidden in the grid
                 *
                 * @deprecated see column_model option
                 */
                'hidden_columns'                    => array(),

                /**
                 * Use these configuration to map columns to input types
                 * e.g. 'description' => 'textarea'
                 *
                 * @deprecated see column_model option
                 */
                'column_type_mapping'               => array(),

                /**
                 * Custom toolbar buttons
                 *
                 * Configure toolbars buttons to be added to all grids or to specific grids
                 * Add configuration in the specific section. Change table_name_here to the table name
                 *
                 * 'global'   => array(
                 *      'help' => array(
                 *          'title'    => 'Help',
                 *          'icon'     => 'icon-info-sign',
                 *          'position' => 'top',
                 *          'class'    => 'btn btn-mini',
                 *          'callback' => new \Laminas\Json\Expr('function(){ alert("i am here");}')
                 *     )
                 * ),
                 *
                 *
                 *  'specific' => array(
                 *      'themes'    => array( // grid ID
                 *          'layout-manager' => array(  // toolbar ID
                 *              'id'         => 'layman',
                 *              'class'      => 'btn btn-mini',
                 *              'title'      => 'Layout Manager',
                 *              'icon'       => 'icon-th-large',
                 *              'position'   => 'bottom',
                 *              'onLoad'     => '',
                 *              'callback'   => new Expr("function(){  your_callback_onclick_function ; }"),
                 *              'attributes' => array(
                 *                  data-id => 'any_attricute to add to the tag'
                 *              )
                 *          )
                 *      )
                 */
                'toolbar_buttons'                   => array(
                    'global'   => array(), //global toolbars to appear on all grids
                    'specific' => array() // grid specific toolbars, index is the gridId
                ),

                /**
                 *
                 * Specify column models for columns. This will overwrite the default settings
                 *
                 * @since 27-05-2013
                 * @see   http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options
                 */
                'column_model'                      => array(
                    'actions'  => array(
                        'viewable' => false
                    ),
                    'id'       => array(
                        'editable'  => false,
                        'editrules' => array(
                            'edithidden' => false
                        ),
                        'formatter' => 'integer'
                    ),
                    'password' => array(
                        'editable' => false,
                        'viewable' => false
                    ),
                    'email'    => array(
                        'formatter' => 'email',
                        'editrules' => array(
                            'email' => true,
                        ),
                    ),
                    'url'      => array(
                        'formatter' => 'link',
                        'editrules' => array(
                            'url' => true,
                        ),
                    )
                ),
                /**
                 * @See http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching&s[]=filtertoolbar
                 */
                'filter_toolbar'                    => array(
                    'enabled'    => true,
                    'showOnLoad' => true,
                    'options'    => array(
                        'searchOperators' => true,
                        'autosearch'      => true,
                        'stringResult'    => true,
                        'defaultSearch'   => 'cn',
                    )
                ),

                /**
                 * Navgrid options
                 *
                 * @see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator
                 */
                'nav_grid'                          => array(
                    'edit'       => true,
                    'add'        => true,
                    'del'        => true,
                    'view'       => true,
                    'refresh'    => true,
                    'search'     => true,
                    'cloneToTop' => false
                ),

                /**
                 * Edit parameters
                 * e.g.  'afterSubmit' => new \Laminas\Json\Expr("function() { alert('test'); }"),
                 *
                 * @see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator
                 */
                'edit_parameters'                   => array(
                    'reloadAfterSubmit' => true,
                    'jqModal'           => true,
                    'closeOnEscape'     => false,
                    'recreateForm'      => true,
                    'bottominfo '       => 'Fields marked with (*) are required'
                ),

                'add_parameters'                    => array(
                    'reloadAfterSubmit' => true,
                    'jqModal'           => true,
                    'closeOnEscape'     => false,
                    'recreateForm'      => true,
                    'checkOnSubmit'     => true,
                    'closeAfterAdd'     => true,

                ),

                'view_parameters'                   => array(
                    'reloadAfterSubmit' => true,
                    'modal'             => true,
                    'jqModal'           => true,
                    'closeOnEscape'     => false
                ),

                'search_parameters'                 => array(
                    'closeOnEscape'  => false,
                    'sFilter'        => 'filters',
                    'multipleSearch' => true

                ),

                'delete_parameters'                 => array(
                    'height' => 'auto'
                ),

                'inline_nav'                        => array(
                    'add'       => false,
                    'del'       => false,
                    'edit'      => false,
                    'cancel'    => false,
                    'save'      => false,
                    'addParams' => array(
                        'useFormatter' => true,
                        'addRowParams' => array(
                            'keys'              => true,
                            'restoreAfterError' => true,
                        )
                    )
                ),

                'form_options'                      => array(
                    'closeAfterAdd'     => true,
                    'reloadAfterSubmit' => true,
                    'jqModal'           => true,
                    'closeOnEscape'     => false,
                    'modal'             => true,
                    'recreateForm'      => true,
                    'checkOnSubmit'     => true,
                    'bottominfo'        => 'Fields marked with (*) are required'
                ),

                /**
                 * This is the default ID field when displaying join table records in the selects
                 */
                'default_association_mapping_id'    => 'id',

                /**
                 * This is the default label/title field when displaying join table records in selects
                 */
                'default_association_mapping_label' => 'title',
            ),